Saturday, 14 September 2013

Bit Tricks

The basic Bit Operations are & (AND) , |(OR) , ^(X-OR), ~(Negation).

Checking nth bit set or not

Let 'x' be the given number.
 (x & (1<<n)) >> n

Setting the nth bit of number
x = ( x | (1<<n) )



Resetting the nth bit of a number
x = ( x & ( ~ ( 1<<n ) ) )

Toggling the nth bit of a number
x = ( x ^ ( 1<<n ) )

Checking whether is a power of 2
x & ( x - 1) == 0 ? print " Power of 2 " : print "Not a power of 2 "

Finding the first bit from LSB which is set
x & ( -x ) -> This gives pow(2,n)

Finding the MSB bit set in an integer
x |= x>>1

x |=  x>>2

x |= x>>4

x |= x>>8

x |= x>>16

n = x - ( x>>1 )

where n is the MSB

This logic work up to 32-bit

No comments:

Post a Comment