英文:
Why is the minimum value for an int in java -2^31 and not -2^31-1
问题
在Java中,我理解int类型大小为32位。Java不支持无符号的数值,因此其中1位用于表示int是否为负数或正数。因此,剩下的31位用来存储数值。最高的31位可以表示的最大值是(2^31)-1,这是int类型在Java中可以容纳的最大值,但为什么它可以一直到-2^31而不是-2^31-1。
英文:
In java I understand that an int is 32 bits in size. Java does not support unsigned values so one bit is used to hold the information on whether the int is negative or positive. So the remaining 31 bits hold the value of the number. The highest 31 bits can go is (2^31)-1 which is the highest value an in t in java can hold but why can it go all the way down to -2^31 and not -2^31-1.
答案1
得分: 2
这与Java并无特定关系,而是所有计算机如何用32位表示整数。但为了回答你的问题:在2^32个可能值中,一半,也就是2^31个值用于表示非负值,包括0在内。因此有2^31 - 1个值用于表示正数,所以最大的是2^31 - 1。
另一半,也就是2^31个值用于表示负数,因此它们一直到 -2^31。
英文:
This doesn't particularly have anything to do with Java, it's how all computing represents integers with 32 bits. But to answer that question: out of 2^32 possible values, half -- 2^31 -- of those values are used to represent nonnegative values, including 0. So there's 2^31 - 1 values to represent positive numbers, so the highest is 2^31 - 1.
The other half -- 2^31 -- are all used to represent negative numbers, so they go all the way down to -2^31.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论