【发布时间】:2015-09-14 13:54:41
【问题描述】:
在 C 和 C++ 中,如果在使用 >> 和 <<(右移和左移运算符)时右操作数为负数,则程序的行为未定义。
考虑以下程序:
#include <iostream>
int main()
{
int s(9);
std::cout<<(s<<-3);
}
g++ 给出以下警告:
[Warning] left shift count is negative [enabled by default]
MSVS 2010 给出以下警告:
warning c4293: '<<' : shift count negative or too big, undefined behavior
现在我很好奇 Java 和 C# 中发生了什么?
我试过以下程序
class left_shift_nagative
{
public static void main(String args[])
{
int a=3;
System.out.println(a<<-3);
System.out.println(a>>-3);
}
}
计划结果:
1610612736
0
轮到C#了:
namespace left_shift_nagative
{
class Program
{
static void Main(string[] args)
{
int s = 3;
Console.WriteLine(s << -3);
Console.WriteLine(s >> -3);
}
}
}
输出:
1610612736
0
输出 1610612736 是怎么来的?这里发生了什么? Java 语言规范 (JLS) 和 C# 语言规范或标准对此有何评论?在 Java 和 C# 中给出负移位计数时,> 运算符如何工作?使用右移时如何得到输出 0?我真的很困惑。
【问题讨论】:
-
它使用位。如果您检查 -3 位,它就像
.... 1101。点很多1111 1111 1111向右移动会将0011移动到0000,因为在那之后它不能做任何事情。 -
我刚刚在这里阅读了 Eric Lippert 的一篇文章。 #8 提到了移位运算符。 informit.com/articles/article.aspx?p=2425867.
标签: java c# c++ bitwise-operators bit-shift