It is caused by the automatic transformation of java. The principle is as follows: 1. 128 is an int integer with 32 bits, the first 24 are all 0 and the last 8 bits are 1000 0000 2. (byte)128 is the first after being transformed into byte. is 1, Java considers it as the complement identifier of a negative number 3. When System.out.println is called, the Java type system will automatically convert the byte type to int. At this time, a signed left shift operation is performed, and the first 24 All bits are 1, and the last 8 bits are 1000 0000, which is still -128. 4, so the output is -128
tip: Java should perform automatic type conversion when doing byte operations, and it does not support unsigned integers. Pay special attention to it. Usually you need to use the & operation to block the wrong bits caused by automatic expansion
It is caused by the automatic transformation of java. The principle is as follows:
1. 128 is an int integer with 32 bits, the first 24 are all 0 and the last 8 bits are 1000 0000
2. (byte)128 is the first after being transformed into byte. is 1, Java considers it as the complement identifier of a negative number
3. When System.out.println is called, the Java type system will automatically convert the byte type to int. At this time, a signed left shift operation is performed, and the first 24 All bits are 1, and the last 8 bits are 1000 0000, which is still -128.
4, so the output is -128
tip: Java should perform automatic type conversion when doing byte operations, and it does not support unsigned integers. Pay special attention to it. Usually you need to use the & operation to block the wrong bits caused by automatic expansion
The value range of byte is -128~127, 128 overflows
128
是一个int
类型整数00000000 00000000 00000000 10000000
, 长度为32
Bitsbyte
类型整数长度为8
位, 所以强制转换后为最后8
位10000000
The first bit from left to right is the sign bit,
0
时值为0
~127
,1
时值为-128
~-1
Call
System.out.println(int)
时 Java 把byte -128
转回int -128
So
(byte) 128 == (int) -128