[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Counting bits



"Timothy L. Nali" <[email protected]>:
> > Eli [email protected] 
> > int byte_ones(int a)
> > // hope this is correct...
> > {
> >         a = (a & 0x55) + (a & 0xAA)/2;          // 0x55 == 01010101b
> [...]
> Note that some compilers might not be smart enough to use logical shift
> ops and instead use expensive division ops.  Just to be safe...
> 
> int byte_ones(int a)
>          a = (a & 0x55) + ((a & 0xAA) << 1);          // 0x55 == 01010101b
                                    ^^^^^^^^^
Let me guess: you're one of the lucky users of the RBO (Reverse Bit Order)
SuperDecryptor from the NSA, where the LSB is the one at the extreme left?

Or did you mean ((a & 0xAA) >> 1)   ;)

My personal preference for byte operands is unsigned char - this ensures
that right shifts are not sign-extended by the most brain dead compiler, and
might use only one byte for the parameter.

-----------------------------------------------------------------------------
Rishab Aiyer Ghosh             "Clean the air! clean the sky! wash the wind!
[email protected]                   take stone from stone and wash them..."
Voice/Fax/Data +91 11 6853410  
Voicemail +91 11 3760335                 H 34C Saket, New Delhi 110017, INDIA