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