简体   繁体   English

在以下情况下,如何计算按位运算符结果的总和?

[英]How do I compute the sum of bitwise operator results in the following case?

The code is as follows:代码如下:

#include <stdio.h>
int main()
{
    int a = 512,b = 32;
    int c = a>>2 + b<<2;
    printf("%d",c);

    return 0;
}

The result I'd expect isn't 512 and rather 128 (a>>2) + 128 (b<<2) as the result.我期望的结果不是 512,而是 128 (a>>2) + 128 (b<<2) 结果。 Why is the output 512?为什么输出是 512? I understand that arithmetic + operator has higher precedence but where does the brackets land?我知道算术 + 运算符具有更高的优先级,但括号落在哪里? Any help is appreciated, thanks.任何帮助表示赞赏,谢谢。

Operator precedence in C states that additive operators have a higher precedence than shifting operators, if you want the expected output of 256 you will need to use parenthesis to force shifting to take place first. C 中的运算符优先级表明加法运算符的优先级高于移位运算符,如果您想要 256 的预期输出,则需要使用括号来强制首先进行移位。 So, int c = a>>2 + b<<2;所以, int c = a>>2 + b<<2; becomes int c = (a>>2) + (b<<2);变为int c = (a>>2) + (b<<2);

As stated in the comments (by @Eugene Sh.), currently it is evaluated as (a>>(2+b)) << 2) and that is undefined behavior, as you are shifting more than the type width.正如评论中所述(@Eugene Sh.),目前它被评估为(a>>(2+b)) << 2)并且这是未定义的行为,因为您移动的范围超过了类型宽度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM