I am trying to right shift an integer by 32 but the result is the same number.
(e.g. 5 >> 32
is 5.)
If I try to do same operation on Byte and Short it works. For example, "(byte)5 >> 8" is 0.
What is wrong with Integer?
I am trying to right shift an integer by 32 but the result is the same number.
(e.g. 5 >> 32
is 5.)
If I try to do same operation on Byte and Short it works. For example, "(byte)5 >> 8" is 0.
What is wrong with Integer?
JLS 15.19. Shift Operators
... If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance.
so shifting 32
is not effective.
A Shifting conversion returns result as an int
or long
. So, even if you shift a byte
, you will get an int
back.
Java code :
public static void main(String s[]) {
byte b = 5;
System.out.println(b >> 8);
int i = 8;
System.out.println(i >> 32);
}
Byte code :
0: iconst_5
1: istore_1
2: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
5: iload_1
6: bipush 8
8: ishr
9: invokevirtual #22 // Method java/io/PrintStream.println:(I)V ==> Using println(int)
12: bipush 8
14: istore_2
15: getstatic #16 // Field java/lang/System.out:Ljava/io/PrintStream;
18: iload_2
19: bipush 32
21: ishr
22: invokevirtual #22 // Method java/io/PrintStream.println:(I)V ==> Using println(int)
25: return