Bitwise shifting array of char’s

You have to shift and compare elementwise.

for(i = 0; i < len; ++i)
    array[i] >>= 3;

for example. If you want to move the bits shifted out of one element to the next, it’s more complicated, say you’re shifting right, then

unsigned char bits1 = 0, bits2 = 0;
for(i = len-1; i >= 0; --i) {
    bits2 = array[i] & 0x07;
    array[i] >>= 3;
    array[i] |= bits1 << 5;
    bits1 = bits2;
}

traversing the array in the other direction because you need the bits from the next higher slot.

Leave a Comment