窄转换为字节后的 128 int 如何变为 -128



我知道在java中字节有8位内存,即从-128到127。我也知道窄铸的概念。并且int失去了一些精度。但是有人可以帮助我理解以下内容吗

    public class PrimitiveTypes {
    public static void main(String[] args) {
        Byte byteVar= (byte) 128;
        System.out.println(byteVar);
    }
}

o/p is -128

请不要告诉我,因为周期为 127 它显示 -128 .我需要这里发生的二进制算术。我能够从网络中找到的是java将整数存储在2的补码中,用于存储负号。所以从 2 的补码

128 变为 10000000

after flipping 11111111

添加 1 位将是

10000000

问题是这100000000变成-128?

答:

谢谢我得到的答案:

我需要将 2 的补码编号 10000000 转换为十进制,例如

you first check if the number is negative or positive by looking at the sign bit. If it is positive, simply convert it to decimal. If it is negative, make it positive by inverting the bits and adding one. Then, convert the result to decimal. The negative of this number is the value of the original binary.
    Interpret 11011011 as a two's complement binary number, and give its decimal equivalent.
        First, note that the number is negative, since it starts with a 1.
        Change the sign to get the magnitude of the number.
            1   1   0   1   1   0   1   1
        ¬   0   0   1   0   0   1   0   0
        +                               1
            0   0   1   0   0   1   0   1
        Convert the magnitude to decimal: 001001012 = 25_16 = 2×16 + 5 = 37_10.
        Since the original number was negative, the final result is -37. 

所以就我而言 10000000成为 01111111加 1 将是 10000000这是 128原始 no 为负数,因为第一位为 1所以-128

在二进制文件中,int 128 看起来像这样。

0000 0000 0000 0000 0000 0000 1000 0000

这是 32 位,4 个字节。

当您键入将其转换为字节时,您会得到最后 8 个二进制数字。

1000 0000

事实证明,这是字节 -128 的二进制表示。

所以结果确实是-128。

二进制中的所有字节值都是这样的:

1000 0000  -> - 128
1000 0001  -> - 127
1000 0010  -> - 126
...
1111 1110 -> -2
1111 1111 -> -1
0000 0000 -> 0
0000 0001 -> 1
0000 0010 -> 2
...
0111 1110 -> 126
0111 1111 -> 127

这应该让你清楚。

你的困惑可能是因为你在想
1000 0000为无符号字节值。在爪哇
有没有无符号字节。第一个位确定符号。
如果有无符号字节(如其他一些语言),
这个二进制值确实是128的,而不是-128的。

最新更新