Monday, 16 June 2008

Bit masks and shifting

bit masking is fun.. but sometimes dangerous if you aren't careful.

to se the Nth bit of a variable:

var |= (1 << N)

to unset the Nth bit of a variable:

var &= ~(1 << N)

you can make an N bit mask by taking the Nth bit and subtracting 1

for b111, use (1<<3)-1
for b11111111, use (1<<8)-1
for bMASK_LENGTH(1)s use (1<<MASK_LENGTH)-1

you can then shift this mask up to wherever you need to mask off some values. If you have certain areas of a variable designated as sub ints, then you can set them thus:

setup:
MASK_START
MASK_LENGTH
MASK = ((1<<MASK_LENGTH)-1) << MASK_START

setting sub int:
var &= ~MASK
var |= newValue<<MASK_START

getting the value back out again is quite simple:

value = ( var & MASK ) >> MASK_START

have fun, but be careful.
Post a Comment