Bitwise Operators

D provides the following binary operators for manipulating individual bits inside of integer operands. These operators all have the same meaning as in ANSI-C.

Table 2-9 D Bitwise Operators

Bitwise Operator Description

&

bitwise AND

|

bitwise OR

^

bitwise XOR

<<

shift the left operand left by the number of bits specified by the right operand

>>

shift the left operand right by the number of bits specified by the right operand

The binary & operator is used to clear bits from an integer operand. The binary | operator is used to set bits in an integer operand. The binary ^ operator returns one in each bit position where exactly one of the corresponding operand bits is set.

The shift operators are used to move bits left or right in a given integer operand. Shifting left fills empty bit positions on the right side of the result with zeroes. Shifting right using an unsigned integer operand fills empty bit positions on the left side of the result with zeroes. Shifting right using a signed integer operand fills empty bit positions on the left side with the value of the sign bit, also known as an arithmetic shift operation.

Shifting an integer value by a negative number of bits or by a number of bits larger than the number of bits in the left operand itself produces an undefined result. The D compiler will produce an error message if the compiler can detect this condition when you compile your D program.

In addition to the binary logical operators, the unary ~ operator may be used to perform a bitwise negation of a single operand: it converts each zero bit in the operand into a one bit, and each one bit in the operand into a zero bit.