rsavchenko
rsavchenko

Reputation: 363

Bitwise operators order of precedence

According to Wikipedia, the bitwise AND operator has higher precedence than the bitwise OR. However wolfram says they are equivalent. Are the following two expressions equivalent?

C &  A | B
C & (A | B)

My thoughts are that they are the same since I believe | and & have the same precedence, so we just evaluate left to right.

Upvotes: 2

Views: 16931

Answers (3)

don bright
don bright

Reputation: 1221

If you give WolframAlpha '|' and '&' it will translate it into bitwise functions like BitAnd(x,y) and BitOr(x,y). The expression of binary operators is ambiguous, but it gets changed into functions which are not ambiguous.

Example: 1 & 2 | 3 will get changed into BitOr[BitAnd[1,2],3], and there is only one way to evaluate those functions. As above commenters noted, Alpha is putting & above | in precedence.

Link: http://www.wolframalpha.com/input/?i=1+%26+2+%7C+3

Interestingly, this feature of translating binary operators '|' and '&' appears to be undocumented as it does not appear in any of the standard Wolfram guides to their operators.

Ref 1: https://reference.wolfram.com/language/tutorial/OperatorInputForms.html

Ref 2: http://reference.wolfram.com/language/guide/BitwiseOperations.html

Some examples for bitwise operators from other languages, high->low

Refs:

Upvotes: 4

joews
joews

Reputation: 30330

In theory any language or logic system could dictate the precedence of its operators. However, in all languages I am familiar with, bitwise (and logical, for that matter) AND has higher precedence than OR.

Given that & and | are fundamental operators and, crucially, (a & b) | c = d does not imply a & (b | c) =d, it seems very unlikely that any real language would leave their relative precedence undefined.

Upvotes: 4

Tommy
Tommy

Reputation: 100622

I don't think they have a natural precedence, unlike say multiplication and division being of greater precedence than subtraction and addition because they can be built from subtraction and addition.

In C & has higher precedence than | so your two statements are not equivalent. I'd guess most languages with C-like syntax will inherit from that.

Upvotes: 3

Related Questions