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 in byte 的 short 值以及 1000 in short = -24 in byte 的情况?
我一直在使用以下逻辑将 short 转换为 byte :
1000 十进制 -> 二进制 = 0000 0011 1110 1000
转换为字节时:xxxx xxxx 1110 1000 相当于:232
我确实注意到正确的答案是二进制值的二进制补码,但是我们什么时候使用二进制补码进行转换,什么时候不使用二进制补码将 3450 从短转换为字节时,我没有使用二进制补码但达到了预期的结果。
谢谢!