Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise shifting array of char's

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 how to do this.

I thought, even though it was an array of chars just stating my_array >>= 1 would shift everything but I am getting an error: "error: invalid operands to binary >> (have ‘char[8]’ and ‘int’)"

The bitwise comparision I am trying to do is with a similar size array initiated to all "0's"...for that I'm getting: "error: invalid operands to binary & (have ‘char *’ and ‘char *’)"

Do I need to convert these array's into something else before I can shift and compare?

Sorry, I was not super clear... All great advice up to this point and I think I am realizing more that there is no super easy way to do this. More specifically, what I am trying to do is shift the bits of the WHOLE char array right 1, adding the bit shifted off the right back to the left most side of the array, do the bitwise compare with another array of same size.

Technically the compare doesn't have to be array with array... I just need the bits. Would it be easier to convert the array's to something else before trying to do the shifts/comparisons?

like image 342
MCP Avatar asked Apr 28 '12 21:04

MCP


People also ask

How do you do bitwise shifting?

The bitwise shift operators move the bit values of a binary object. The left operand specifies the value to be shifted. The right operand specifies the number of positions that the bits in the value are to be shifted.

What is shift left bitwise?

The bitwise shift operators are the right-shift operator ( >> ), which moves the bits of an integer or enumeration type expression to the right, and the left-shift operator ( << ), which moves the bits to the left.

What is Bitshift used for?

Bit shifting is used when the operand is being used as a series of bits rather than as a whole. In other words, the operand is treated as individual bits that stand for something and not as a value. Bit shifting is often used in programming and has at least one variation in each programming language.


1 Answers

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.

like image 164
Daniel Fischer Avatar answered Oct 12 '22 14:10

Daniel Fischer