Friday, February 10, 2012

Set single bit integer

Sometime you may lose your mind on how to operate with single bit in an integer, moreover if you are not using bit operation for a long time. This is a quick refresh to deal with single bit operation.

Given variable a type of int

To set the nth bit
a |= (1 << n)

To clear the nth bit
a &= ~(1 << n)

To toggle the nth bit
a ^= (1 << n)

To get nth bit value
a >> n & 1