TAGS :Viewed: 6 - Published at: a few seconds ago

[ C++ - Bit shifting returning negative numbers ]

I'm having some trouble trying to use bit shifting in C++.

I have a char a = 160, and char b = 0. The value of a is 0b10100000. I want to shift the leftmost bits of a into b, so that b would have the value 2 (0b10). By my logic, this should do it:

b = (b << 2) | (a >> 6);

However, when I check the value in b, it's -2 and not 2, as I would expect it to be. Casting it to an unsigned char changes it's value to 254.

What am I doing wrong?

Answer 1


Both types must be unsigned:

unsigned char a = 160;
unsigned char b = 0;
b = (b << 2) | (a >> 6);

is exactly the same as:

unsigned char c = a >> 6;