Click to See Complete Forum and Search --> : bit operations


js1234
July 28th, 2005, 09:25 AM
Hi,

I was hoping I could get some insight on the best way to remove a bit from an array of bytes.

For example:

I have an unsigned char data[10];

I want to remove bit 5 from the second byte of the array and then shift the remaining bits to the left (the end of the array can be zero padded).

Does anyone know of an efficient way to accomplish this?

Thanks!

freddyflintstone
July 28th, 2005, 09:40 AM
You want to start by checking if std::bitset in <bitset> suits your requirements.

D_Drmmr
July 28th, 2005, 03:28 PM
...or else std::vector<bool>.

You can also implement it yourself and use the bit-shift operators >> and <<. For just one byte it would be something like this:

// erase bit with index 'bit' (0 is least significant), shift bits > 'bit' one bit back
erase_bit(unsigned char& c, const int bit)
{
c = (c & (0x7F >> (7 - bit))) | ((c & (0xFE << bit)) >> 1);
}


By the way, when working with bit-arrays, it is easier to use unsigned values. Also, using 32 bit values is faster, since it reduces the number of elements in your array, compared to 8 bit values.