java - 为什么(byte)128等于-128
大家讲道理
大家讲道理 2017-04-18 10:10:02
0
3
685
    System.out.println((byte) 128);//-128
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
阿神

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

刘奇
  1. 128 是一个 int 类型整数 00000000 00000000 00000000 10000000, 长度为 32 Bits

  2. byte 类型整数长度为 8 位, 所以强制转换后为最后 810000000

  3. The first bit from left to right is the sign bit, 0 时值为 0~1271 时值为 -128~-1

  4. Call System.out.println(int) 时 Java 把 byte -128 转回 int -128

  5. So (byte) 128 == (int) -128

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template