-
Enhancement
-
Resolution: Unresolved
-
P4
-
6
-
Fix Understood
When the shift amount for an integer is specified as a literal (immediate) value that is greater than 31, a warning message would be desirable. For example,
"Warning: (int) << 56 is equivalent to (int) << 24.
The same applies for longs having a shift greater than 63 (or less than 0).
$ cat Rfe.java
public class Rfe {
private byte[] buffer = new byte[] {1, 0, 0, 0, 0, 0, 0, 0};
public static void main(String[] args) {
Rfe rfe = new Rfe();
System.out.println("Buggy long value: " + rfe.getLongBuggy(0));
System.out.println("Correct long value: " + rfe.getLong(0));
}
public Rfe() {}
public long getLongBuggy(int offset) {
return ((buffer[offset] & 0xFF) << 56)
| ((buffer[offset + 1] & 0xFF) << 48)
| ((buffer[offset + 2] & 0xFF) << 40)
| ((buffer[offset + 3] & 0xFF) << 32)
| ((buffer[offset + 4] & 0xFF) << 24)
| ((buffer[offset + 5] & 0xFF) << 16)
| ((buffer[offset + 6] & 0xFF) << 8)
| ((buffer[offset + 7] & 0xFF) );
}
public long getLong(int offset) {
return (((long)buffer[offset] & 0xFFL) << 56)
| (((long)buffer[offset + 1] & 0xFFL) << 48)
| (((long)buffer[offset + 2] & 0xFFL) << 40)
| (((long)buffer[offset + 3] & 0xFFL) << 32)
| (((long)buffer[offset + 4] & 0xFFL) << 24)
| (((long)buffer[offset + 5] & 0xFFL) << 16)
| (((long)buffer[offset + 6] & 0xFFL) << 8)
| (((long)buffer[offset + 7] & 0xFFL) );
}
}
"Warning: (int) << 56 is equivalent to (int) << 24.
The same applies for longs having a shift greater than 63 (or less than 0).
$ cat Rfe.java
public class Rfe {
private byte[] buffer = new byte[] {1, 0, 0, 0, 0, 0, 0, 0};
public static void main(String[] args) {
Rfe rfe = new Rfe();
System.out.println("Buggy long value: " + rfe.getLongBuggy(0));
System.out.println("Correct long value: " + rfe.getLong(0));
}
public Rfe() {}
public long getLongBuggy(int offset) {
return ((buffer[offset] & 0xFF) << 56)
| ((buffer[offset + 1] & 0xFF) << 48)
| ((buffer[offset + 2] & 0xFF) << 40)
| ((buffer[offset + 3] & 0xFF) << 32)
| ((buffer[offset + 4] & 0xFF) << 24)
| ((buffer[offset + 5] & 0xFF) << 16)
| ((buffer[offset + 6] & 0xFF) << 8)
| ((buffer[offset + 7] & 0xFF) );
}
public long getLong(int offset) {
return (((long)buffer[offset] & 0xFFL) << 56)
| (((long)buffer[offset + 1] & 0xFFL) << 48)
| (((long)buffer[offset + 2] & 0xFFL) << 40)
| (((long)buffer[offset + 3] & 0xFFL) << 32)
| (((long)buffer[offset + 4] & 0xFFL) << 24)
| (((long)buffer[offset + 5] & 0xFFL) << 16)
| (((long)buffer[offset + 6] & 0xFFL) << 8)
| (((long)buffer[offset + 7] & 0xFFL) );
}
}