PenguinEngineer PenguinEngineer - 2 months ago 7x
C Question

Read a single bit from a buffer of char

I would to implement a function like this:

int read_single_bit(unsigned char* buffer, unsigned int index)

where index is the offset of the bit that I would want to read.

How do I use bit shifting or masking to achieve this?

buffer[index/8] & (1u<<(index%8))

should do it (that is, view buffer as a bit array and test the bit at index).


buffer[index/8] |= (1u<<(index%8))

should set the index-th bit.

Or you could store a table of the eight shift states of 1 and & against that

unsigned char bits[] = { 1u<<0, 1u<<1, 1u<<2, 1u<<3, 1u<<4, 1u<<5, 1u<<6, 1u<<7 }; 

If your compiler doesn't optimize those / and % to bit ops (more efficient), then:

 unsigned_int / 8  == unsigned_int >> 3
 unsigned_int % 8  == unsigned_int & 0x07  //0x07 == 0000 0111


 buffer[index>>3] & (1u<<(index&0x07u))  //test
 buffer[index>>3] |= (1u<<(index&0x07u)) //set