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

  • Buried in cloud files? We can help with Spring cleaning!

    Whether you use Dropbox, Drive, G-Suite, OneDrive, Gmail, Slack, Notion, or all of the above, Dokkio will organize your files for you. Try Dokkio (from the makers of PBworks) for free today.

  • Dokkio (from the makers of PBworks) was #2 on Product Hunt! Check out what people are saying by clicking here.


Bit Manipulation

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



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);




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.



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);





Comments (0)

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