Contact US

Log In

Come Join Us!

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It's Free!

*Tek-Tips's functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here


Working with bit arrays by Clairvoyant1332
Posted: 7 Aug 03

There have been a few times when I've found it usefull to define what is essentially a bit array.  For example I'll define a variable like char flags[100]; and treat it as an array of 800 bits.  This is usefull if you want to send a large number of binary flags over a network.

Accessing a single bit in this array does involve a bit of math that might not be immediately obvious to someone reading your code, so here are a few #define's you can use.

#define ISBITSET(x,i) ((x[i>>3] & (1<<(i&7)))!=0)
#define SETBIT(x,i) x[i>>3]|=(1<<(i&7));
#define CLEARBIT(x,i) x[i>>3]&=(1<<(i&7))^0xFF;

Just like any array, the starting index is 0.

Here, x is your char array and i is your index into the array.  So if you want to look at bit index 9 (the 10th bit) in your array, the bit you want is in the second byte ( x[1] ) two bits over ( x[1]&1 ).  In general, you take the index and divide it by 8 ( x[i/8] or x[i>>3] ) to get the byte you want, then mod the index by 8 ( (i%8) or (i&7) )to get the proper bit index within the byte and take 2 to that power ( (1<<(i&7)) ) to create the bitmask to strip out the bit you want ( x[i>>3] & (1<<(i&7)) ).

The set of macros above assume little endian bit ordering within the array.  If you've defined your own array, this shouldn't matter.  If you're working with someone else's array however, for example when reading a monochrome TIFF file, you may need to use big endian bit ordering.  The #define's below use big endian.

#define ISBITSET(x,i) ((x[i>>3] & (1<<(7-(i&7))))!=0)
#define SETBIT(x,i) x[i>>3]|=(1<<(7-(i&7)));
#define CLEARBIT(x,i) x[i>>3]&=(1<<(7-(i&7)))^0xFF;


Back to C FAQ Index
Back to C Forum

My Archive

Close Box

Join Tek-Tips® Today!

Join your peers on the Internet's largest technical computer professional community.
It's easy to join and it's free.

Here's Why Members Love Tek-Tips Forums:

Register now while it's still free!

Already a member? Close this window and log in.

Join Us             Close