Advertisement Jump to content


This topic is now archived and is closed to further replies.


Bit manipulation

This topic is 5895 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Please recommend me some goods book for bit manipulation in C. For instance, I need to know the fastest routines to determine which bit is set in a long int. Thanks, Arshad

Share this post

Link to post
Share on other sites
Uhm... I may not be understanding what you're asking, but you don't really need a book on it. Say you want to know if the first bit is set. Do this:

if (variable&1){
// bit 0 is set

if you want to know if the second is set:

if (variable&2){
// bit 1 is set

and for the third:

if (variable&4){
// bit 2 is set

Each of the numbers you use (1,2,4,8,etc) is simply 2 to the power of whatever bit you're checking. Just remember that the first bit is bit 0, not bit 1.

I think. I haven't slept much lately, so my brain's math side may be fried.

-Arek the Absolute

[edited by - Arek the Absolute on December 1, 2002 3:24:25 PM]

Share this post

Link to post
Share on other sites
#define BIT_X(x) (1 << x)

Checking if a bit is set:
if ((var & BIT_X(bit)) == BIT_X(bit))
(or as Arek said):
if (var & BIT_X(bit))

Setting a bit:
var |= BIT_X(bit);

Un-setting a bit:
var &= ~BIT_X(bit);

I think those should work ok. BIT_X(bla) is actually very rare. Normally, you''d use a set of flags in an enum or set of #defines, eg:
enum tFontProperties
FNT_BOLD = 0x01,
FNT_ITALIC = 0x04,

If you need explanations for this stuff, google for them first, and post if you don''t find anything.

Hope that helps,

John B

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!