Let's take it one step at a time.
Integer.parseInt("11010100", 2)
- this is the int value 212. This is, by the way, needless; you can just write: 0b11010100
.
0b11010100 << 1
is the same as 0b110101000
, and is 424.
You then cast it to a byte: (byte)(0b11010100 << 1)
. The bits beyond the first 8 all get lopped off, which leaves 0b10101000, which is -88. Minus, yes, because in java bytes are signed.
You then silently cast this -88 back up to int, as you assign it to an int value. It remains -88, which means all the top bits are all 1s.
Hence, the final value is -88
.
If you want to see 168
instead (which is the exact same bits, but shown unsigned instead of signed), the usual trick is to use & 0xFF
, which sets all bits except the first 8 to 0, thus guaranteeing a positive number:
byte b = (byte) (0b11010100 << 1);
System.out.println(b); // -88. It is not possible to print 168 when printing a byte.
int asUnsigned = b & 0xFF;
System.out.println(asUnsigned); // 168.
// or in one go:
System.out.println(((byte) (0b11010100 << 1)) & 0xFF); // 168
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…