在 java 中显式转换时 short 128 = byte -128 怎么样?

How is short 128 = byte -128 while explicit casting in java ?

import java.util.Scanner;

public class ShortToByte{
  public static void main (String args[]){
    int i=0;
    while (i<6){
      Scanner sinput = new Scanner (System.in);
      short a = sinput.nextShort();
      byte b = (byte) a;
      System.out.println("Short value : " + a + ",Byte value : " + b);
      i++;
    }
  }
}

我试图了解不同数据类型之间的转换,但我很困惑,因为 128 的短值如何 = -128 字节以及 1000 的短值如何 = -24 字节?

我一直在使用以下逻辑将 short 转换为 byte:

1000 十进制 -> 二进制 = 0000 0011 1110 1000

转换为字节时:xxxx xxxx 1110 1000 相当于:232

我确实注意到正确答案是二进制值的二进制补码,但是我们什么时候使用二进制补码来转换,什么时候不用,因为在将 3450 从短字节转换为字节时我没有使用二进制补码,但实现了想要的结果。

谢谢!

来自java datatypes

  • byte:byte数据类型为8位有符号二进制补码整数。最小值为-128,最大值为127(含)

因此128溢出为-128。

您从 shortbyte 的转换是 缩小原始转换 JLS, Section 5.1.3,声明:

A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

(大胆强调我的)

数字类型已在 Java 中签名。短 128,以位表示为

00000000 10000000

缩小为8位如下:

10000000

... 即 -128。现在 1 位不再被解释为 +128;现在它是 -128,因为二进制补码是如何工作的。如果设置了第一位,则该值为负数。

1000 也有类似情况。短 1000,以位表示为

00000011 11101000

缩小为8位如下:

11101000

... 即 -24.