Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitshifting in C++ producing the wrong answer

Tags:

c++

shift

I tried running the following code code:

char c = (2 << 7) >> 7

which should return 0 because 2 has this binary representation as a char:

0 0 0 0 0 0 1 0

After 7 shifts left, we get

0 0 0 0 0 0 0 0

Then, after seven shifts right, we get

0 0 0 0 0 0 0 0

However, I'm getting the result as 2, not 0.

The compiler says that 2 << 7 is 256, but it's a char and so it shouldn't be 256.

I understand that the 2 << 7 will be calculated as ints and the answer will be put into c so 256 >> 7 is 2.

I tried to cast 2 to char (ex: (char)2>>7) but it doesn't work either.

I'm trying to extract each bit from the char, so I wrote this code:

char c = 0x02;
for(int i=0;i<7;i++)
{
    char current = (c<<i)>>7;
}

How can I get each bit? What's wrong with my way?

like image 811
MyNick Avatar asked Jun 07 '14 18:06

MyNick


2 Answers

The result of an arithmetic shift operation with one operand being an int in C++ is always an int. Therefore, when you write

current = (c << i) >> 7;

C++ will interpret (c << i) and (c << i) >> 7 as ints, casting back to a char only when the assignment is done. Since the temporary values are ints, no overflow occurs and the result should come out to the integer result casted to a char.

Hope this helps!

like image 147
templatetypedef Avatar answered Sep 25 '22 22:09

templatetypedef


To get each bit, you could write:

(c >> i) & 0x01

Advantage: It works for any integer type.

like image 42
JohnB Avatar answered Sep 26 '22 22:09

JohnB