2013年5月13日 星期一

面試必備 -- BIT MASK

Set Specific Bit

value = value | (1 << bit)

#define SET_BIT(x, y) ((x) = (x) | ((1)<<(y)))

Clear Specific Bit

value = value & ~(1 <<bit)

#define CLEAR_BIT(x, y) ((x) = (x) & ~((1)<<(y)))

Inverse Specific Bit

value = value ^ (1 << bit)

#define INVERSE_BIT(x, y) ((x) = (x) ^ ((1)<<(y)))

Get Specific Bit

ret = (value >> bit) & 1

#define GET_BIT(x, y) ((x)>>(y) & 1)

Bit Count

code:
int counter = 0;
while ( input ) {
    counter++;
    input &= (input - 1);
}

沒有留言:

張貼留言