0

Possible Duplicate:
Left shifting with a negative shift count

Consider my code follows

int main()
{
    int k=1;
    k=k<<-1;
    printf("%d",k);
}

o/p

-2147483648

Why the output is like this.I know negative no's are stored in 2's complement but here is there any use of this concept of -2s complement.Kindly give me some idea.

4

3 回答 3

3

k << -1; // Before the OP edit

and

k = k<<-1;

These statements are undefined behavior in C.

Using a negative value in the right operand of the bitwise left or right shift operator is undefined behavior in C (see C99, 6.5.7).

于 2012-10-15T12:11:22.543 回答
2

-2147483648 结果的原因 - 如果您在 x86 处理器上测试它 - 是移位计数被限制为 31(请参阅“英特尔架构软件开发人员手册第 2 卷:指令集参考”)。所以你得到 1<<31,它等于 0x80000000,当打印为有符号的 32 位整数时,它变成 -2147483648。

于 2012-10-15T12:18:38.010 回答
1

如果第二个操作数为负,则移位操作的结果是不确定的。

http://msdn.microsoft.com/en-us/library/f96c63ed%28v=vs.80%29.aspx
为什么我得到一个负值位移的奇怪结果?

于 2012-10-15T12:12:15.287 回答