1

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?

Gregor Menih
  • 5,036
  • 14
  • 44
  • 66

1 Answers1

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;
Hubi
  • 1,629
  • 15
  • 20