|
|
Bit shifting allows you to shift the bits of an integer value to the left or right. The following is a table of bit shifting operators and a description of what they do.
Operator | Description |
---|---|
<< | Shifts bits to the left, adding zeros from the right |
>> | Shifts bits to the right, copying the sign bit (leftmost bit) from the left |
>>> | Shifts bits to the right, adding zeros from the left |
These operators are binary and take two operands. The left operand is the integer value on which to perform the shift, and the right operand is the number of bits to shift. Left-shifting by powers of two will perform an integer division, and right-shifting by powers of two will multiply the value. For example, let's say we had the decimal value 2, which would be represented in binary by the value 00000010 in a byte. An alternative to directly multiplying this value by 8 would be to bit shift the value three places to the left.
byte number = 2; // binary 00000010
We could then left-shift the bits three places, as follows:
number = number << 3;
When shifting the bits three places to the left and filling in zeros from the right, our binary notation would be 00010000, which is the decimal value of 24, equaling 16. This is the same as multiplying 2 by 23.
Note | The previous code of bit shifting the value of the variable number could have also been performed using the assignment left-shift operator, as follows: number <<= 3; |
|
|