好奇:为什么移位运算符的优先级低于加法运算符?
我想知道为什么分别相当于乘法和除法的移位运算符(<< 和 >>)的优先级确实低于加法运算符(例如“+”)。
换句话说:
int a = 1 + 2 * 8; //yields 17
而:
int a = 1 + 2 << 3; //yields 24
任何人都知道这种行为背后的原因是什么?
注意:请不要回答我“因为规格是这么说的”!
预先感谢大家。
编辑:我意识到左移可以通过对左操作数本身求和来获得。可能是这个原因吗?
I'm wondering why the shift operators (<< and >>), being equivalent to a multiplication and a division respectively, do have less priority than an additive operator, such the "+".
In other words:
int a = 1 + 2 * 8; //yields 17
whereas:
int a = 1 + 2 << 3; //yields 24
Anyone knows what's the reason behind this behavior?
NOTE: Please, don't answer me "because the specs say so"!
Thank you all in advance.
EDIT: I realized that a left-shift can be obtained by summing the left operand by itself. May be this the reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
算术运算符和按位运算符的相对优先级是无关紧要的,因为无论如何你都不应该一起使用它们。如果你想将一个整数视为一个位数组,那么就不要对它进行加法和减法就像一个数字。如果您想将整数视为数字,则不要像位数组一样对它进行移位、或运算和与运算。
坦率地说,如果我按照自己的方式行事,就不会对整数进行位移操作;您必须将整数转换为 BitArray 类型,这样就不会进行算术运算。事实上,整数被视为位数组和数字,这是一个由于历史原因而存在的不幸的设计缺陷。
位移位是一种乘法和除法的概念是一个奇怪的概念。位移位是位移位,而不是乘法。
The relative priority of arithmetic operators and bitwise operators is irrelevant because you should never be using them together anyway. If you want to treat an integer as an array of bits, then don't be adding and subtracting it like a number. If you want to treat an integer as a number, then don't be shifting, or-ing and and-ing it like an array of bits.
Frankly if I had my way there would be no bit shifting operations on integers; you'd have to cast the integer to a BitArray type, that would not have arithmetic on it. The fact that ints are treated as both bit arrays and numbers is an unfortunate design flaw that exists for historical reasons.
The notion that bit shifting is a kind of multiplication and division is a strange one; bit shifting is bit shifting, not multiplication.
如果我将其归因于一个理性的决定,我会说这是因为在某些常见情况下很方便,例如在构造位模式时:
A + B << 8
将在倒数第二个有效字节中标记位 A 和 B。当然,它也可能只是随机优先级分配,因为 Dennis Ritchie 不知道它在哪里更适合(我公然假设 C# 继承了 C 的运算符优先级)。不幸的是,他不再在这里告诉我们了。 :(
If I were to ascribe a rational decision to it, I'd say it's because convenient in some common situations, such as when constructing bit patterns:
A + B << 8
would mark bits A and B in the second-to-least significant byte.It could just as well just be a random priority allocation as well, of course, because Dennis Ritchie didn't have any idea where it would fit better (I blatantly assume C# inherits the operator priorities from C). Unfortunately, he isn't here to tell us anymore. :(