为什么Java Integer.MIN_VALUE是-2 ^ 31而不是-2 ^ 31 + 1像c ++ [英] Why Java Integer.MIN_VALUE is -2^31 but not -2^31+1 like c++

查看:70
本文介绍了为什么Java Integer.MIN_VALUE是-2 ^ 31而不是-2 ^ 31 + 1像c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在检查Java文档,并看到Integer.MIN_VALUE为-2 ^ 31:

I'm checking the Java doc, and seeing that Integer.MIN_VALUE is -2^31:

一个常量,它保​​存一个int可以具有的最小值-2 ^ 31.

A constant holding the minimum value an int can have, -2^31.

在C ++中,32位带符号整数"long"具有不同的MIN值:

While in C++, the 32 bits signed integer "long" has a different MIN value:

LONG_MIN:long int类型的对象的最小值-2147483647(-2 ^ 31 + 1)以下*

LONG_MIN: Minimum value for an object of type long int -2147483647 (-2^31+1) or less*

我很困惑为什么它们不同以及Java如何获得-2 ^ 31?在Java中,如果一个整数有32位并且第一位用于符号,则-2 ^ 31 + 1更具逻辑性,对吗?

I am very confused why they are different and how Java get -2^31? In Java, if an integer has 32 bits and the first bit is used for sign, -2^31+1 is more logical, isn't it?

推荐答案

32位数字中最高有效位的值是2 ^ 31,并且在有符号整数中为负值时,该值是-2 ^ 31.我想C ++使用-2 ^ 31 + 1作为MIN_VALUE,因为这意味着它具有与MAX_VALUE相同的绝对值,即2 ^ 31-1.这意味着整数可以存储-MIN_VALUE,而Java中不是这种情况(这可能会引起一些有趣的错误).

The value of the most significant bit in a 32 bit number is 2^31, and as this is negative in a signed integer the value is -2^31. I guess C++ uses -2^31+1 as the MIN_VALUE because this means it has the same absolute value as MAX_VALUE i.e. 2^31-1. This means an integer could store -MIN_VALUE, which is not the case in Java (which can cause some fun bugs).

这篇关于为什么Java Integer.MIN_VALUE是-2 ^ 31而不是-2 ^ 31 + 1像c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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