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 从短字节转换为字节我没有使用二进制补码但达到了预期的效果结果。
谢谢!
最佳答案
从 short
到 byte
的转换是一个缩小的原始转换。 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 typeT
. 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/