Thomas Sampson

Bit Manipulation Tip

Leave a comment

The following bitwise operation can be used to find /isolate the position of the right most bit in the data.

myVar &  -myVar

How does this work?

Thius method relies on the fact that you are using two’s complement to store a negative number (usually the case) rather than using a sign bit.

myVar = 5                   // hence myVar=0101

-myVar=-5                 // hence -myVar=1011 – in two’s complement, hence….

myVar & -myVar = ?   // ? = 0001,

// Hence showing that the right most bit of myVar is infact in the far right position

Try it out! This will work with any bit pattern!

Advertisements

Author: tomtech999

I have recently graduated with a 1st class degree in MComp Games Software Development at Sheffield Hallam University, focusing primarily on application development in C++, with experience in graphics programming, scripting languages, DVCS/VCS and web technology. In my spare time I enjoy Drumming, Reading and Snowboarding!

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