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

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s