Byte-to-Bits and Bits-to-Byte Operations

What commands are available for extracting individual bits from a byte?
In pseudo-pseudocode:

char data; 
char bit[8]; 

for (int i = 0; i < 8; i++) {
     bit[i] = extract(data, i);

I can't find a function or operation to do that...
Thanks, Nick

'&' (logical and), '>>' (shift right), '<<' (shift left), etc.

In actual code:

char data; 
bool bit[8]; 
// fill data 
for(int i = 0; i < 8; i++) {
     bit[i] = ((data >> i) & 0x01);

Remy Lebeau (Team B)

And the data with the bit you want e.g.

 bit[i] = data & (1 << i);

Russell Hind

You use the shift (<< and >>) operators, and bit masking (&).
Something like:

char extract(char data, int i) {
     return (data >> i) & 1 ;

Untested, unfinished, but that's the idea.
Read up about those operators.

Alan Bellingham
Team Thai Kingdom

Use the bitwise and operator '&' and a bitmask.

BYTE BitMask[]={ 1, 2, 4, 8, 16, 32, 64, 128};
bool BitIsSetF( BYTE ValueToTest, BYTE ZeroBasedBitNumber ) { 
     return ValueToTest&ZeroBasedBitNumber;

Note that C++ doesn't have a built in power operator (odd really considering that Pascal and BASIC both do).
Instead you will have to use the pow() math function which is probably slow or bit shifting eg:

bool BitIsSetF( DWORD ValueToTest, int ZeroBasedBitNumber) { 
     return ValueToTest&( 1<<ZeroBasedBitNumber);

Andrue Cope
Bicester, UK