按位运算符 [英] Bitwise operator predence

查看:71
本文介绍了按位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在类似C的语言中遇到过几次陷阱,这是这样的:

A gotcha I've run into a few times in C-like languages is this:

original | included & ~excluded   // BAD

由于优先级,此解析为:

Due to precedence, this parses as:

original | (included & ~excluded)   // '~excluded' has no effect

有人知道针对 bitwise 运算符的三个独立优先级的原始设计决策背后的原因吗?更重要的是,您是否同意该决定,为什么?

Does anyone know what was behind the original design decision of three separate precedence levels for bitwise operators? More importantly, do you agree with the decision, and why?

推荐答案

至少从我同意该顺序,因为它与算术运算符的最相似的相对顺序(+*和取反)是相同的.

I agree with the order because it is the same relative order as the relative order of the arithmetic operators that they are most similar to (+, * and negation).

您可以在此处看到&*以及|+的相似性:

You can see the similarity of & vs *, and | vs + here:


A  B | A&B A*B | A|B A+B 
0  0 |  0   0  |  0   0
0  1 |  0   0  |  1   1
1  0 |  0   0  |  1   1
1  1 |  1   1  |  1   2

通过以下公式可以看出按位非和取反的相似性:

The similarity of bitwise not and negation can be seen by this formula:


~A = -A - 1

这篇关于按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆