Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Working with bit arrays

Programming

Working with bit arrays

by  Clairvoyant1332  Posted    (Edited  )
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
Code:
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.

Code:
#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,
Code:
x
is your char array and
Code:
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 (
Code:
x[1]
) two bits over (
Code:
x[1]&1
). In general, you take the index and divide it by 8 (
Code:
x[i/8]
or
Code:
x[i>>3]
) to get the byte you want, then mod the index by 8 (
Code:
(i%8)
or
Code:
(i&7)
)to get the proper bit index within the byte and take 2 to that power (
Code:
(1<<(i&7))
) to create the bitmask to strip out the bit you want (
Code:
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.

Code:
#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
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top