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

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

问题描述

我不明白为什么一个字节可以取的最小值是 -128.我可以看到最高值是127,因为它是二进制的01111111,但是一个只有8位的-128如何表示,一个其中用于标志?正 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.

谁能帮我解释一下.

推荐答案

答案是二进制补码.

简而言之,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 开头的数字都是负数),但接下来的七位不是被解释为应用符号位的无符号数.

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.

Two 的补码并不是非常复杂,但是初步了解二进制补码是什么以及它的工作方式和原因可能超出了 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天全站免登陆