I’m understanding how >>> works. To do it I have this program:
public class Main {
public static void main(String[] args)
{
short i = 130;
byte b = (byte)i;
String a = Integer.toBinaryString(256 + (int) b);
System.out.println(Integer.toBinaryString(i));
System.out.println(a.substring(a.length() -8));
System.out.println(b);
byte c = (byte) (b >>> 2);
String x = Integer.toBinaryString(256 + (int) c);
System.out.println(x.substring(x.length() -8));
System.out.println(c);
}
}
And I get this output:
10000010
10000010
-126
11100000
-32
To show as binary, I found here how to show a byte as a binary string.
Operator >>> will add zeros, but I get this:
-126
11100000
-63
Instead of:
-126
10100000
-32
It is adding a 1 instead of 0:
11100000
10100000
What am I doing wrong? Maybe I don’t understand anything.
The problem is that
b >>> 2is first promotingbto an int with value -126, i.e.When you shift that right by 2 with zero-extension, you get:
When that’s then converted back to a byte, it just lops off the first three words, giving 11100000, which is what you’re seeing.
See section 15.19 of the JLS for more details about bit-shifting.