Re: bit operations and parity



Ian Shef wrote:
Mayeul <mayeul.marguet@xxxxxxx> wrote in
news:4a708393$0$9973$426a74cc@xxxxxxxxxxxx:

RVic wrote:
<snip>
Anyway, if all you want to do is to check for even parity, you need
neither. All you need to do is count the number of 1's in a byte and
check this number is even.

(On a side note, I know of no direct way to do that in Java.

boolean even = true;
for(int i = 0; i < 8; i++) {
if((theByte & (1 << i)) != 0) {
even = !even;
}
}

Maybe?)
Or a table lookup could be used. There are only 256 values in the table. The table could be computed offline and stored in the source code, or the table could be computed at initialization (perhaps by using the counting routine that you showed above). Also, I suspect that there may be faster ways to count. Depending upon how the jvm is implemented, having (1 << i) in the loop may be inefficent. It may be more efficient to do
if ((theByte & 1) != 0)
as the test, and
theByte >>= 1 ;
for the shift at the end of each iteration. Only one shift is needed per iteration, so there are no questions about whether the processor has a barrel shifter.

To compute the parity of a byte, you can do

byte data = ...;
int parity = data ^ (data >> 4);
parity ^= parity >> 2;
parity ^= parity >> 1;
parity &= 1;

Extending the procedure to short, int, long, and char is left as an
exercise for the reader. (Extending it to float and double is left
as an exercise in futility.)

--
Eric.Sosman@xxxxxxx
.



Relevant Pages

  • Re: Lesson: Flowing through chord sequences
    ... positions before you begin the exercise. ... Take the following chord sequence: ... Try not to shift beyond one fret for any of the lines. ...
    (rec.music.makers.guitar.jazz)
  • Re: A little knowledge...
    ... It's way more effective than exercise alone to burn off the ... you could cut also 450kcals from your diet and therefore hit ... >to a normal diet will help, but to shift it fast I've always found ... with a two pound a week weight loss for someone well ...
    (rec.sport.rugby.union)
  • RE: listing prime numbers in a range (Beginning Perl exercise)
    ... > stuart>Hi David, ... > stuart>I figure that the exercise wouldn't be in the ... and move the 'print' to after the loop. ... When 'shift' has no argument, it shifts '@_' which is parameter ...
    (perl.beginners)
  • Re: circular shifting a vector/matrix - Problem
    ... corrCoef = zeros(1, numColMatrix01); ... for shiftSize = 1:numColMatrix01, ... Are you sure you want to shift like this (iteration 1, 1 shift, ...
    (comp.soft-sys.matlab)
  • security considerations for: set x dir/[*] dir/*
    ... The following steps for the iteration are: ... contents of $is under the control of an attacker (and this shell ...
    (comp.unix.shell)