Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

shift - Bitshifting in C++ producing the wrong answer

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...