×
INTELLIGENT WORK FORUMS
FOR COMPUTER PROFESSIONALS

Are you a
Computer / IT professional?
Join Tek-Tips Forums!
• Talk With Other Members
• Be Notified Of Responses
• Keyword Search
Favorite Forums
• Automated Signatures
• 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.

# C FAQ

## Programming

 Working with bit arrays by Clairvoyant1332 faq205-3999 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;Dennis Back to C FAQ Index Back to C Forum

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:

• Talk To Other Members
• Notification Of Responses To Questions
• Favorite Forums One Click Access
• Keyword Search Of All Posts, And More...

Register now while it's still free!