简体   繁体   中英

Bitshift operation with signed and unsigned

I was doing a bitshift operation of an int and was surprised that it didn't come out as expected.

int i, res;
i = 0x80000000;
res = i>>1;                //results in 0xc0000000
res = (unsigned int) i>>1; //results in 0x40000000

how is it possible that a shift of a bit in an integer does only work to the 31st bit?

What you are seeing is probably arithmetic bit shift .

when shifting to the right, the leftmost bit (usually the sign bit in signed integer representations) is replicated to fill in all the vacant positions (this is a kind of sign extension).

The C99 standard 6.5.7§5 says:

The result of E1 >> E2 is E1 right-shifted E2 bit positions. [...] If E1 has a signed type and a negative value, the resulting value is implementation-defined.

So the result could be anything the compiler writers decided it to be. They probably decided to extend the sign bit, the compiler doc should mention it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM