Wednesday, January 13, 2016

Fun Program to Count 1s

int count_1_bit(char b) {
int tot = 0;
if ((b & 1) == 0) tot++; 
if ((b & 2) == 0) tot++;
if ((b & 4) == 0) tot++;
if ((b & 8) == 0) tot++;
if ((b & 16) == 0) tot++;
if ((b & 32) == 0) tot++;
if ((b & 64) == 0) tot++;
if ((b & 128) == 0) tot++;
return tot;
}

#define __const_hweight8(w)     \
    ((unsigned int)         \
     ((!!((w) & (1ULL << 0))) + \
      (!!((w) & (1ULL << 1))) + \
      (!!((w) & (1ULL << 2))) + \
      (!!((w) & (1ULL << 3))) + \
      (!!((w) & (1ULL << 4))) + \
      (!!((w) & (1ULL << 5))) + \
      (!!((w) & (1ULL << 6))) + \
      (!!((w) & (1ULL << 7)))))


static inline unsigned int hweight8(unsigned int w)
{
        unsigned short res = (w & 0x55) + ((w >> 1) & 0x55);
        res = (res & 0x33) + ((res >> 2) & 0x33);
        return (res & 0x0F) + ((res >> 4) & 0x0F);
}