Re: Parity check of a word



On Mon, 29 Aug 2005 01:37:27 -0700, Krishanu Debnath wrote:

....

> Following code works for even parity scheme.
>
> int parity (unsigned x)
> {
> unsigned y;
>
> y = x ^ (x >> 1);
> y = y ^ (y >> 2);
> y = y ^ (y >> 4);
> y = y ^ (y >> 8);
> y = y ^ (y >>16);
> return y & 1;
> }

However it assumes that int/unsigned int are wider than 16 bits
which is not portable; if unsigned is 16 bits wide then y >> 16 has
undefined behaviour. If you want an unsigned type can can store at least
32 bits use unsigned long, or maybe uint_least32_t in C99.

Lawrence
.



Relevant Pages

  • Re: Parity check of a word
    ... Lawrence Kirby wrote: ... >> Following code works for even parity scheme. ... >> int parity ... Prev by Date: ...
    (comp.lang.c)
  • Re: Parity check of a word
    ... > Ben Pfaff wrote: ... >>int parity ... I'm afraid it doesn't work. ... Prev by Date: ...
    (comp.lang.c)