X++ Bitwise Operators

January 30, 2008

Bitwise operations are performed at the individual bits. In other words, the value is converted into binary format and the bitwise operators will act on each and every digit.

Bitwise operation is not very widely used in business solution development. The only time I remember using one was to track a series of states. The advantage is the set of states (true or false) could be altered in one operation. However, readability is not good.

Dynamics Ax provides a set of operators to perform such operation. They will be discussed subsequently. The examples you will find subsequently are base on 32-bit integers. The rest of the operators are Arithmetic and Assignment Operators, and Relational Operators.

& (AND)

This operator performs a binary AND on two expressions.

Syntax

expression1 & expression2

Example

print 10 & 8; //1010 AND 1000
pause; // 1000 -> 8

| (OR)

This operator performs a binary OR to two expressions.

Syntax

expression1 | expression2

Example

print 10 | 8; //1010 OR 1000
pause; // 1010 -> 10

^ (XOR)

This operator performs a binary XOR to two expressions.

Syntax

expression1 ^ expression2

Example

print 10 ^ 8; //1010 XOR 1000
pause; // 0010 -> 2

~ (NOT)

This operator performs a bitwise NOT to the expression on the right.

Syntax

~ expression

Example

print ~10; //NOT 1010
pause; // 11111111111111111111111111110101 -> -11

<< (Left Shift)

This operator requires two operands. Expression on the right specifies the number of bits to shift. A left shift takes the number of bit specified from the left and moves it to the right.

The common use of left shift is to multiply an integer by a power of 2. The syntax is equivalent to expression1 * 2 expression2.

Syntax

expression1 << expression2

Example

print 123 << 3; // 00000000000000000000000001111011 << 3
pause; // 00000000000000000000001111011000 -> 984

>> (Right Shift)

This operator is a reverse of Left shift. It also requires two operands and the expression on the right denotes the number of bits to shift. The different is that it will shift the bits from the right to the left instead.

Syntax

expression1 >> expression2

Example

print 984 >> 3; // 00000000000000000000001111011000 << 3
pause; // 00000000000000000000000001111011 -> 123

0 comment :