Showing posts with label bit twiddling. Show all posts
Showing posts with label bit twiddling. Show all posts

Wednesday, April 25, 2007

#34

How simple can your code be if you want to return the firs set/unset bits?
Answer:

    c & -c or c & (~c + 1); //Return first bit set
    ~c & (c + 1); //Return first unset bit

#30

How can you round up to the next highest power of 2?

Answer:

    unsigned int v;
    v--;
    v = v >> 1;
    v = v >> 2;
    v = v >> 4;
    v = v >> 8;
    v = v >> 16;
    v++;

#27

Reverse the bits of an unsigned integer.


Answer:

    #define reverse(x) \
    (x=x>>16(0x0000ffff&x)<<16,>
    x=(0xff00ff00&x)>>8(0x00ff00ff&x)<<8,>
    x=(0xf0f0f0f0&x)>>4(0x0f0f0f0f&x)<<4,>
    x=(0xcccccccc&x)>>2(0x33333333&x)<<2,>
    x=(0xaaaaaaaa&x)>>1(0x55555555&x)<<1)

#26

How do we test most simply if an unsigned integer is a power of two?

Answer:

    f = !(v & (v - 1)) && v;