开发者

storing negative numbers

In this code below

int开发者_如何学JAVA main()
{
int  a = -1;
printf("%d",a>>1);
return 0;
}

Why it is giving output -1.


bit-shifting is defined only on unsigned types, for signed types it is implementation-defined. And this is a useful refinement by R..

Strictly speaking, it is defined for signed types whenever the value is positive and the result does not overflow, and right shift is implementation-defined for negative values. Left shift, on the other hand, is undefined for negative values

┌───┬──────────────┬──────────────────────────────────┬────────────────────────┐
│   │ Unsigned     │ Signed, positive                 │ Signed, negative       │
├───┼──────────────┼──────────────────────────────────┼────────────────────────┤
│<< │ well-defined │ well-defined, except on overflow │ undefined behaviour    │
│>> │ well-defined │ well-defined                     │ implementation-defined │
└───┴──────────────┴──────────────────────────────────┴────────────────────────┘


Because -1 is 1111111...111 in binary. a>>1 operation will "sign extend" the sign bit, so you get 1111111...111 again.


Most compilers choose to interpret >> on signed numbers to be arithmetic shift. Thus since the number is initially negative (i.e. the MSB bit is 1), after a right shift, that bit is replaced by another 1 to preserve the sign, ergo you end up with -1 as you started.


The >> operator on a signed value may perform an arithmetic or logical shift, depending on the compiler. Arithmetic shifts retain the sign bit, so -1 (which on a 2-s complement machine, which these days is pretty much the only variety you will encounter) will remain -1 when right-shifted. (Note that the C standard explicitly does not specify whether >> on a signed number is an arithmetic or logical shift. It is always a logical shift on unsigned numbers, though.)


The definition of bit-shifting on signed values is implementation-dependent. Check your compiler's docs for how it handles it.


In Memory signed integer number stored as 2's complement if sign int and when data is read from memory {%d} it's converted into original form so here 2's complement of -1 will stored in memory let say integer take 2 byte so 2's complement of -1 is 1111 1111 1111 1111

After perform a>>1 It will change 0111 1111 1111 1111 now As we know that when data is read from memory it's again converted to 0 complement so take 2's complement of 0111 1111 1111 1111 It will be like 1000 0000 0000 0001 which is equal to -1

Note: 2's complement of +ve number is same as original binary representation 2's complement is only for -ve number. In C number always stored as 2's complement form

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜