| 
  • Earn a $50 Amazon gift card for testing a new product from the makers of PBworks. Click here to apply.

  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

View
 

Bit Manipulation

Page history last edited by Kenneth Finnegan 10 years, 11 months ago

These macros will be useful if you need to store a lot of yes/no info, in what is known as a bitfield.  A bitfield is nothing more than a regual int, except that you manipulate each individual bit, storing either a 1 or a 0 in each.

 

Code:

unsigned int flags;

// Set a bit

flags = flags | 1<<bitindex;

// Clear a bit

flags = flags & ~(1<<bitindex);

// Flip a bit

flags = flags ^ 1<<bitindex;

// Test a bit

if (flags & 1<<bitindex)

     printf("Bit %d is set!\n", bitindex);

 

 

Usage:

Mind that all the bits are zero indexed, so usually, a char will have bits 0-7, short 0-15, ints 0-31, long long 0-63.  It's usually best to have them be unsigned, but that shouldn't make that much of a difference.

 


Extensions:

All of the code can be put into a set of macros so you don't have to retype it every place.

#define SETBIT(bitfield, bitindex) (bitfield |= 1<<bitindex)

#define UNSETBIT(bitfield, bitindex) (bitfield &= ~(1<<bitindex))

#define TOGGLEBIT(bitfield, bitindex) (bitfield ^= 1<<bitindex)

#define TESTBIT(bitfield, bitindex) (!!(bitfield&(1<<bitindex)))

// And can be used like so:

SETBIT(flags, 3);

if (TESTBIT(flags, 3))

     printf("Bit %d is set!\n", bitindex);

 


Sources:

http://en.wikipedia.org/wiki/Bit_manipulation

http://stackoverflow.com/questions/127027/how-to-check-my-byte-flag

Comments (0)

You don't have permission to comment on this page.