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 int
s 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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…