The bitwise operators operates on integral types (int and long). Before explaining how bitwise operators work, you should have an idea of how integers are represented in the binary form. As mentioned by the official primitive data type tutorials, the int data type is a 32-bit signed 2's complement integer, whose value ranges from -2^32 to 2^32-1, inclusively. On the other hand, the long data type is a 64-bit signed 2's complement integer, whose value ranges from -2^64 to 2^64-1, inclusively. In both cases, the highest order bit of int and long shows the sign of the value and is not part of the numeric value, where 0 being positive and 1 being negative.
For example, an int value of 1 in binary form looks like this
00000000000000000000000000000001while an int value of -1 in binary form looks like this
11111111111111111111111111111111The negative value is transformed in 2 steps:
Step 1: bitwise complement of +1, such that 00000000000000000000000000000001 becomes 11111111111111111111111111111110 Step 2: add 1, such that 11111111111111111111111111111110 becomes 11111111111111111111111111111111Given a negative value, where the highest (leftmost) bit is 1, you can work out what value the binary form represents in 2 steps:
Step 1: bitwise complement of the binary value, such that 11111111111111111111111111111011 becomes 00000000000000000000000000000100 Step 2: add 1, such that 00000000000000000000000000000100 becomes 00000000000000000000000000000101Therefore, the original binary form represents -5.
The bitwise operators
Operator | Name | Example | Result | Description |
---|---|---|---|---|
a & b | and | 6 & 9 | 0 | 1 if both bits are 1, or 0 if either bit is 0 |
a | b | or | 6 | 9 | 15 | 1 if either bit is 1, or 0 if both bits are 0 |
a ^ b | xor | 6 ^ 9 | 15 | 1 if both bits are different, 0 if both bits are the same |
~a | not | ~9 | -10 | Inverts the bits. (equivalent to +1 and then change sign) |
n << p | left shift | 60 << 2 | 240 | Shifts the bits of n left p positions. Zero bits are shifted into the low-order positions. |
n >> p | right shift | 60 >> 2 | 15 | Shifts the bits of n right p positions. If n is a 2's complement signed number, the sign bit is shifted into the high-order positions. |
n >>> p | unsigned right shift | -60 >>> 20 | 4095 | Shifts the bits of n right p positions. Zeros are shifted into the high-order positions. |
No comments:
Post a Comment