1

The code comes from the link C puzzles

int CountBits (unsigned int x )
{
      static unsigned int mask[] = { 0x55555555,
          0x33333333,
          0x0F0F0F0F,
          0x00FF00FF,
          0x0000FFFF
          } ;

          int i ;
          int shift ; /* Number of positions to shift to right*/
          for ( i =0, shift =1; i < 5; i ++, shift *= 2)
                  x = (x & mask[i ])+ ( ( x >> shift) & mask[i]);
          return x;
}
xxx7xxxx
  • 774
  • 6
  • 18
  • 2
    Possible duplicate: http://stackoverflow.com/q/3815165/395718 – Dialecticus Apr 04 '14 at 10:31
  • http://stackoverflow.com/questions/109023/how-to-count-the-number-of-set-bits-in-a-32-bit-integer/15979139#15979139 Check this answer. It explains the code. – Arvind Apr 04 '14 at 10:33
  • @Dialecticus Sorry, I'll flag this question. – xxx7xxxx Apr 04 '14 at 10:34
  • Note that this code possibly invokes undefined behaviour: the `int` type is guaranteed to be 2 bytes long (16bit). This code assumes `sizeof(int)` is four. Either use `int32_t` (defined in `stdint.h`), or use `long` to be on the safe side. (though I haven't seen a C implementation where the int wasn't at least 32bits, it could be possible) – Elias Van Ootegem Apr 04 '14 at 10:52
  • @EliasVanOotegem using c compiler for AVR processors results in 16bit ints – vlad_tepesch Apr 04 '14 at 10:59
  • @vlad_tepesch: Aha, thanks for backing up my comment. I have no experience with embedded programming, but I figuered that, if ever you encounter such a situation (16bit ints), it'd be on a compiler for specific architectures. – Elias Van Ootegem Apr 04 '14 at 12:11

0 Answers0