Consider the expression x>>y , here x is signed int with left most bit is 1 then is the result depend on machine ? I have tried for signed int with left most bit is 0 i got same result, but i don't know about given case.
Asked
Active
Viewed 235 times
0
-
no, but if you access a 32 bit word with an array of characters you need to be concerned. – kenny Jan 31 '15 at 12:40
-
1possible duplicate of [Does Bit Shift Depends on Endianness?](http://stackoverflow.com/questions/7184789/does-bit-shift-depends-on-endianness) – VHarisop Jan 31 '15 at 12:40
-
1in C bit shifts are an arithmetic operation; so they work on values, not representations – M.M Jan 31 '15 at 12:49
-
ok, that means shifting is only depend on compiler not on machine, am i right ? – Jan 31 '15 at 13:05
1 Answers
2
There are no unambiguous "leftmost" or "rightmost" bits (which depends on convention), but most significant and least significant bits. The sign bit on a 2's complement machine is the most significant bit.
>>
uses zero extension if the shifted is an unsigned
.
Positive signed values behave like positive unsigned values. The >>
of a negative quantity, however, is implementation defined, but wherever I have used it, negative numbers have been sign-extended.
Also, left-shifting something to the sign bit of a signed quantity is undefined behaviour, so for most portable programs it is best to use bitshift tricks only to unsigned values.

Antti Haapala -- Слава Україні
- 129,958
- 22
- 279
- 321
-
further info; The sign bit is the MSB in all representations supported by C (2's comp, 1's comp, sign-magnitude). so you can just say it is always the MSB. – M.M Jan 31 '15 at 12:58