32 lines
977 B
Plaintext
32 lines
977 B
Plaintext
== Why is this an issue?
|
|
|
|
Since an `int` is a 32-bit variable, shifting by more than +/-31 is confusing at best and an error at worst. When the runtime shifts 32-bit integers, it uses the lowest 5 bits of the shift count operand. In other words, shifting an `int` by 32 is the same as shifting it by 0, and shifting it by 33 is the same as shifting it by 1.
|
|
|
|
|
|
Similarly, when shifting 64-bit integers, the runtime uses the lowest 6 bits of the shift count operand and shifting `long` by 64 is the same as shifting it by 0, and shifting it by 65 is the same as shifting it by 1.
|
|
|
|
== How to fix it
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public int shift(int a) {
|
|
int x = a >> 32; // Noncompliant
|
|
return a << 48; // Noncompliant
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public int shift(int a) {
|
|
int x = a >> 31;
|
|
return a << 16;
|
|
}
|
|
----
|
|
|
|
include::../rspecator.adoc[] |