位运算符优先级

发布于 2024-09-19 06:27:04 字数 271 浏览 1 评论 0原文

我在类 C 语言中遇到过几次的问题是:

original | included & ~excluded   // BAD

由于优先级,它解析为:

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

有谁知道按位的三个独立优先级的原始设计决策背后是什么?运营商?更重要的是,您同意这个决定吗?为什么?

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岛徒 2024-09-26 06:27:04

至少从 C 起,运算符就具有此优先级。

我同意这个顺序,因为它与它们最相似的算术运算符(+* 和否定)的相对顺序相同。

您可以在这里看到 &* 以及 |+ 的相似之处:

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

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

~A = -A - 1

The operators have had this precedence since at least C.

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
一指流沙 2024-09-26 06:27:04

为了扩展 Mark Byers 的答案,在布尔代数(电气工程师广泛使用来将逻辑电路简化到最少的门数并避免竞争条件)中,传统是按位 AND 优先于按位 OR。 C只是遵循这个既定的传统。请参阅http://en.wikiversity.org/wiki/Boolean_algebra#Combining_Operations

就像普通代数一样,其中
乘法优先于
另外,AND 优先(或
优先级)高于 OR。

To extend Mark Byers' answer, in boolean algebra (used extensively by electrical engineers to simplify logic circuits to the minimum number of gates and to avoid race conditions), the tradition is that bitwise AND takes precedent over bitwise OR. C was just following this established tradition. See http://en.wikiversity.org/wiki/Boolean_algebra#Combining_Operations :

Just as in ordinary algebra, where
multiplication takes priority over
addition, AND takes priority (or
precedence) over OR.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文