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?
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!
To get each bit, you could write:
(c >> i) & 0x01
Advantage: It works for any integer type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With