在C ++中将1 <<2和1 << 3相加时的输出很奇怪 [英] Weird output when summing 1<<2 and 1<<3 in C++
本文介绍了在C ++中将1 <<2和1 << 3相加时的输出很奇怪的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我只是尝试在C ++中进行一些操作.这是我尝试过的:
So I was just trying some bit manipulation in C++. Here is what I tried:
int a = 1<<2;
cout<<a;
这将输出显示为4
.
int a = 1<<3;
cout<<a;
这将输出显示为8
但是当我这样做时:
int a = 1<<2 + 1<<3;
cout<<a;
它给出的输出为64
.为什么这样?
It gives the output as 64
. Why so?
我也尝试过:
int a = 1<<2;
int b = 1<<3;
cout<<a + b;
这将输出如预期的那样作为12
.
Which gives the output as 12
as expected.
推荐答案
这是因为加法运算符的优先级高于移位.换句话说,您的第二个示例等效于1 << (2 + 1) << 3
This is because addition has a higher operator precedence than bitshift. In other words, your second example is equivalent to 1 << (2 + 1) << 3
此外,由于位移是左关联的,因此它与(1 << (2 + 1)) << 3
相同.简化为8 << 3
,即64
.
Furthermore, since bitshifting is left-associative, it's the same as (1 << (2 + 1)) << 3
. This simplifies to 8 << 3
, which is 64
.
这篇关于在C ++中将1 <<2和1 << 3相加时的输出很奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文