| 
View
 

Bit Manipulation

This version was saved 17 years, 6 months ago View current version     Page history
Saved by Kenneth Finnegan
on February 8, 2009 at 2:50:53 pm
 

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:

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 a char will have bits 0-7, ints 0-31 (usually) and so on.

 


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.