java - 在java中显式转换时,short 128 = byte -128如何?

标签 java type-conversion byte short explicit-conversion

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 字节的值如何?

我一直在使用以下逻辑将短格式转换为字节:

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

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

我确实注意到正确的答案是二进制值的二进制补码,但是什么时候我们使用二进制补码进行转换,什么时候不使用二进制补码将 3450 从短字节转换为字节我没有使用二进制补码但达到了预期的效果结果。

谢谢!

最佳答案

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

关于java - 在java中显式转换时,short 128 = byte -128如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49499388/

相关文章:

java - 使用 Tomcat 访问 Java 类

mysql、预处理语句和自动类型转换

r - 将变量从字符转换为数字,但不包括一个字符变量

c++ - 将 `double` 转换为 `string`

c - 通过引用将字节加载到 C 字符串中

java - 如何在java中将二进制字符串转换为十六进制并通过Uart端口发送

java - Java 中的桌面屏幕流

java - 如何在不使用 PowerMock 中的 PrepareFor 注释的情况下模拟私有(private)方法?

c# - 将整数转换为字节但不溢出

java - 如何正确使用 JdbcTemplate.update 和 KeyHolder?