Example: Bitwise operators in expressions
These are the examples of bitwise operators in expressions.
Symbol (Function) | Description | Example: If tag1 = 5 (binary 0000 0000 0000 0101) and tag2 = 3 (binary 0000 0000 0000 0011), then: |
& (Bitwise AND) | Returns an integer with a bit set to 1 if both of the corresponding bits in the original numbers are 1. Otherwise, the resulting bit is 0. | tag1 & tag2 returns 1 (binary 0000 0000 0000 0001) |
| (Bitwise inclusive OR) | Returns an integer with a bit set to 1 if either or both of the corresponding bits in the original numbers are 1. If both bits are 0, the resulting bit is 0. | tag1 | tag2 returns 7 (binary 0000 0000 0000 0111) |
^ (Bitwise exclusive XOR) | Returns an integer with a bit set to 1 if either of the corresponding bits in the original numbers is 1. If both bits are 1 or both are 0, the resulting bit is 0. | tag1 ^ tag2 returns 6 (binary 0000 0000 0000 0110) |
>> (Right Shift) | Shifts the bits within the left operand by the amount specified in the right operand. The bit on the right disappears. Either a 0 or a 1 is shifted in on the left depending on whether the integer is signed or unsigned. With unsigned integers, 0 is always shifted in on the left. With signed integers, a 0 is shifted in when the number is positive (that is, the leftmost bit--the sign bit--is 0), and a 1 is shifted in when the number is negative (that is, the leftmost bit--the sign bit--is 1). In other words, with signed integers, the sign of the number is always maintained. | tag1 >> 1 returns 2 (binary 0000 0000 0000 0010) |
<< (Left Shift) | Shifts the bits within the left operand by the amount specified in the right operand. The bit on the left disappears and a 0 is shifted in on the right. If the left bit is a 1, an overflow occurs, and an error message appears. To prevent this, use the bitwise AND (&&) operator in an expression. For example, (dev << 1) && 65535, where 65535 is 1111 1111 1111 1111 in binary form. Where dev is a tag name whose value is being shifted left. | tag1 << 1 returns 10 (binary 0000 0000 0000 1010) |
~ (Complement) | Gives the ones complement of a number. For example, use this operator to reverse every bit within the number so that every 1 bit becomes a 0 and vice versa. | ~ tag1 r eturns -6 (binary 1111 1111 1111 1010) |
Provide Feedback