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

  • Browse and search Google Drive and Gmail attachments (plus Dropbox and Slack files) with a unified tool for working with your cloud files. Try Dokkio (from the makers of PBworks) for free. Now available on the web, Mac, Windows, and as a Chrome extension!

View
 

Bit Manipulation

Page history last edited by Kenneth Finnegan 12 years, 6 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.