• ### Popular Now

• 11
• 14
• 12
• 10
• 11

#### Archived

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

# Bit manipulation

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

## 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 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 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_UNDERLINE = 0x02,  FNT_ITALIC = 0x04,  FNT_STRIKEOUT = 0x08,  FNT_SUPERSCRIPT = 0x10,  FNT_SUBSCRIPT = 0x20};

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

Hope that helps,

John B