Bitwise Operators (Advanced Topic)
The following operators act upon the individual binary bits that comprise the operand values.
These operators can be applied to any values of any ordinal type (int, long, or any enumerated type).
Sign bits are not treated specially. For example, if a negative integer is shifted to the right, the sign bit will shift along with everything else, resulting in a positive integer (or zero).
If any of the operands are of the type long, then the result type of each operator is long. Otherwise, the result type is int.
General Form | Meaning / Remarks |
---|---|
ord1 & ord2 |
and Each bit in the result value is 1 if (and only if) both of the corresponding bits in ord1 and ord2 are 1. |
ord1 | ord2 |
Each bit in the result value is 1 if (and only if) either or both of the corresponding bits in ord1 and ord2 are 1. |
ord1 ^ ord2 |
exclusive or Each bit in the result value is 1 if (and only if) either, but not both, of the corresponding bits in ord1 and ord2 are 1. |
~ord |
complement (1's complement) The result comprises all of the bits of ord, but with every bit flipped; i.e., every 0 is replaced with 1, and every 1 is replaced with 0. |
ord << n |
shift left The result is determined by shifting the bits of ord to the left by n places. (n must be a whole number.) High order bits are lost; low order bits are populated with zeros. If n is negative, the bits are shifted to the right by |n| places. |
ord >> n |
shift right The result is determined by shifting the bits of ord to the right by n places. (n must be a whole number.) Low order bits are lost; high order bits are populated with zeros. If n is negative, the bits are shifted to the left by |n| places. |