...
Code Block |
---|
|
int x = -50;
x = x + 2;
x >>>>>= 2;
|
The >>>=
operator is a logical right shift; it fills the leftmost bits with zeroes, regardless of the number's original sign. Using logical right shift for division produces an incorrect result when the dividend (x
in this example) contains a negative value. Arithmetic right shift (the >>=
operator) can replace division, as shown in the following example:
Code Block |
---|
|
int x = -50;
x = x + 2;
x >>>>>= 2;
|
However, the result is less maintainable than making the division explicit. Refer to guideline NUM04-J. Use shift operators correctly for examples of sign extension with respect to the shift operators.
...
Code Block |
---|
|
// b[] is a byte array, initialized to 0xff
byte[4] b = new byte[] {-1, -1, -1, -1};
int result = 0;
for (int i = 0; i < 4; i++) {
result = ((result << 8) + b[i]);
}
|
...
Code Block |
---|
|
byte[4] b = new byte[] {-1, -1, -1, -1};
int result = 0;
for (int i = 0; i < 4; i++) {
result = ((result << 8) + (b[i] & 0xff));
}
|
...
Code Block |
---|
|
byte[4] b = new byte[] {-1, -1, -1, -1};
int result = 0;
for (int i = 0; i < 4; i++) {
result = ((result << 8) | (b[i] & 0xff));
}
|
Exceptions
INT03-EX1EX0: Bitwise operations may be used to construct constant expressions.
Code Block |
---|
|
int limit = 1 << 17 - 1; // 2^17 - 1 = 131071
|
INT03-EX2EX1: Data that is normally treated arithmetically may be treated with bitwise operations for the purpose of serialization or deserialization. This is often required for reading or writing the data from a file or network socket, It may also be used when reading or writing the data from a tightly packed data structure of bytes.
Code Block |
---|
|
int value = /* interesting value */
Byte[] bytes[] = new Byte[4];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = value >> (i*8) & 0xFF;
}
/* bytes[] now has same bit representation as value */
|
...