Advertisement

Bit manipulation

Started by December 01, 2002 08:51 AM
1 comment, last by asyed 21 years, 11 months ago
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
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]
-Arek the Absolute"The full quartet is pirates, ninjas, zombies, and robots. Create a game which involves all four, and you risk being blinded by the sheer level of coolness involved." - Superpig
Advertisement
#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
The best thing about the internet is the way people with no experience or qualifications can pretend to be completely superior to other people who have no experience or qualifications.

This topic is closed to new replies.

Advertisement