为什么Java中的字节范围为-128到127? [英] Why is the range of bytes -128 to 127 in Java?

查看:176
本文介绍了为什么Java中的字节范围为-128到127?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么一个字节可以采用的最低值是 -128 。我可以看到最高值是 127 ,因为它是二进制的 01111111 ,但是如何表示 -128 只有8位,其中一位用于标志?正128已经是8位,即 10000000 ,然后你需要第9位来表示负号。

I don't understand why the lowest value a byte can take is -128. I can see that the highest value is 127, because it's 01111111 in binary, but how does one represent -128 with only 8 bits, one of which is used for the sign? Positive 128 would already be 8-bit, i.e. 10000000, and then you would need a 9th bit to represent the negative sign.

有人可以帮我解释一下。

Could someone please help explain this to me.

推荐答案

答案是两个补充

简而言之,Java(和大多数现代语言)不使用带符号幅度表示来表示有符号整数。换句话说,8位整数不是符号位,后跟7位无符号整数。

In short, Java (and most modern languages) do not represent signed integers using signed-magnitude representation. In other words, an 8-bit integer is not a sign bit followed by a 7-bit unsigned integer.

相反,负整数表示在一个称为二进制补码的系统中,这样可以更容易地在硬件中进行算术处理,并且还消除了具有正零和负零的潜在模糊性。消除负零的副作用是在范围的底部总有一个额外的负数。

Instead, negative integers are represented in a system called two's complement, which allows easier arithmetic processing in hardware, and also eliminates the potential ambiguity of having positive zero and negative zero. A side effect of eliminating negative zero is that there is always one extra negative number available at the bottom of the range.

二进制补码系统的另一个有趣特性是第一位有效地作为符号指示符(即所有以1开头的数字)是负的),但接下来的7位不能自己解释为应用符号位的无符号数。

Another interesting property of two's complement systems is that the first bit does effectively function as a sign indicator (i.e. all numbers beginning with the bit 1 are negative), but the next seven bits are not to be interpreted on their own as an unsigned number to which the sign bit is applied.

两个补码并不是很糟糕虽然很复杂,但是对两个补码是什么以及它的工作原理和原因的初步掌握可能超出了SO答案的范围。从维基百科的文章开始,或者在术语中谷歌获取更多资源。

Two's complement isn't terribly complicated, but getting an initial good grip on what two's complement is and how and why it works is probably beyond the scope of an SO answer. Start with the Wikipedia article, or google the term for more resources.

要尝试简要地解决关于-128的查询,生成二进制补码数的基本思路是采用无符号形式的数字,反转所有位并添加一个。因此,无符号128是10000000.反转,它是01111111,并且添加一个再次获得10000000。所以在二进制补码系统中,10000000明确地为-128而不是+128。大于或等于+128的数字不能使用二进制补码系统以8位表示,因为它们与负数形式不一致。

To try to briefly address your query about -128, the fundamental idea behind generating a two's complement number is to take the unsigned form of the number, invert all of the bits and add one. So unsigned 128 is 10000000. Inverted, it's 01111111, and adding one gets 10000000 again. So in a two's complement system, 10000000 is unambiguously -128 and not +128. Numbers greater than or equal to +128 simply cannot be represented in 8 bits using a two's complement system because they would be ambiguous with the forms of negative numbers.

这篇关于为什么Java中的字节范围为-128到127?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆