Operators in TypeScript have rules of Precedence and Associativity that determine how expressions are evaluated. Here I describe Precedence and Associativity separately.
Precedence rules determine which operators should be applied first. For operators with different precedence, the one with the highest precedence is always applied first. You will see that when an expression mixes & and | then that evaluation must be done in the correct order. In an expression, the operator with the highest precedence is grouped with an operand first, then the next highest operator will be grouped with these operands, and that process continues. The following table describes the precedence of bitwise operators in decreasing order, in other words, number 5 (Five) has less precedence than all the other operators.
For example, if we write this code:
- var a = 2,
- b = 3,
- c = 4,
- d = 2,
- e = 5;
- var x = a | b & c << d ^ e;
Then the result is that a is 7 because the preceding example is evaluated that way.
(a) c<<d will be evaluated first, due to precedence and the result will be 16.
(b) After Step a, the remaining part, b&16 or 3&16 will be evaluated and the result will be 0 (zero).
(c) After Step b, the remaining part, 0^e or 0^5 will be evaluated and the result will be 5.
(d) After Step c, the remaining part, a|5 or 2|5 will be evaluated and the result will be 7, in other words, var x=7 is the final result.
Associativity
If in any expression contains several bitwise operators of the same Precedence, then how to solve that expression? The answer of this question is
Associativity, and bitwise operators, which have the same precedence in a single expression or say when two or more operators (such as (<<) and (>>)) with the same precedence can be applied to the same operand, the left to right Associativity will cause the left-most operator to be applied first. And if two of the same operators are applied in a single statement, then left to right associativity will cause (
inseated of (~) bitwise negation operator).
For example, if we write this code:
- var a = 2,
- b = 3,
- c = 4,
- d = 3,
- e = 2,
- val;
- var y = a | b | b & c << d ^ e;
Then the result is that a is 7 because the preceding example is evaluated that way.
(a) c<<d will be evaluated first, due to precedence and the result will be 16.
(b) After Step a, the remaining part, b&16 or 3&16 will be evaluated and the result will be 0 (zero).
(c) After Step b, the remaining part, 0^e or 0^5 will be evaluated and the result will be 5.
(d) After Step c, the remaining part, a|b|5 will be evaluated from left to right, in other words first, a | b or 2 | 3 will be evaluated and the result will be 3.
(e) And finally 3|b or 3|5 will be evaluated and the result will be 7, in other words, var y==7.
The following examples show how to do Precedence and Associativity of Bitwise operators in TypeScript. Create a program using Bitwise operators.
BitWise .ts