Reputation: 13671
I got the following code:
int main(int argc, char *argv[])
{
char c = 128;
c = c >> 1;
printf("c = %d\n", c);
return 0;
}
Running the above code on Windows XP 32 bit, I got the result: -64
. Why -64
?
Upvotes: 3
Views: 12062
Reputation: 8961
Variable c
is signed. Changing the declaration to unsigned char c
... will yield a result of 64.
Upvotes: 0
Reputation: 700910
Because the char
type is a signed 8-bit integer (in the implementation of C that you are using). If you try to store the value 128 in it, it will actually be -128.
The bits for that would be:
10000000
Shifting a negative number will keep the sign bit set (as your implementation uses an arithmetic shift):
11000000
The result is -64.
Upvotes: 9
Reputation: 101
The C standard doesn't specify whether char is signed or unsigned. In this case it looks like you're getting a signed char, with a range from -128 to +127. Assigning 128 to it rolls round and leaves you with -128, so c>>1 is -64.
If you specify c as "unsigned char", c>>1 will be 64.
As the comment says, right-shifting a negative value is undefined by the standard so it's just luck that it comes out as -64.
Upvotes: 3
Reputation: 28932
You are using type char
which by default is signed. Signed char
s have a range of -128 to 127. which means char c = 128 really sets c
to -128. (This is because most processors use two's complement to represent negative numbers) Thus when you shift right you get -64.
Bottom line is that when doing bit manipulations, use unsigned types to get the results you expect.
Upvotes: 0