Bitwise shifting array of char's

后端 未结 7 1590
谎友^
谎友^ 2020-12-03 17:41

I have got an array of chars that I\'m trying to bitwise shift right >>, then & with another array. I think I have got the wrong idea of

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 18:30

    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.

提交回复
热议问题