Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the max integer in java 2^31 - 1 and not 2^31 [duplicate]

Sorry if this is a really basic question, but why is there a minus one for the positive side?

Does it have to do with the zero being stored or something? I thought computing the highest possible decimal number for binary would just be to add the powers of two up, like for a 3 bit unsigned it would be

1*2^0 + 1*2^1 + 1*2^2 = 7

Shouldn't the same rule apply for java integers? Thanks

like image 896
Lucas Ou-Yang Avatar asked Oct 12 '12 20:10

Lucas Ou-Yang


People also ask

Why is 2,147,483,647 the max int value?

The number 2,147,483,647 (or hexadecimal 7FFFFFFF16) is the maximum positive value for a 32-bit signed binary integer in computing. It is therefore the maximum value for variables declared as integers (e.g., as int ) in many programming languages.

Can int type in Python3 Cannot represent a number greater than 2 31 1?

int in Python3 has no max limit maxsize has been added. sys. maxsize is 2**31-1 on a 32-bit environment and 2**63-1 on a 64-bit environment, like sys. maxint in Python2.

What is the max number for int in Java?

The int type in Java can be used to represent any whole number from -2147483648 to 2147483647. Why those numbers? Integers in Java are represented in 2's complement binary and each integer gets 32 bits of space.

What is the max 32-bit integer?

A 32-bit signed integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). A 32-bit unsigned integer. It has a minimum value of 0 and a maximum value of 4,294,967,295 (inclusive).


2 Answers

Because Java can support max signed int as 0x7fffffff which is 2^31-1.

2^31 = 0x80000000 is negative so Positive is 2^31-1

Binary level comparasion would be:

10000000000000000000000000000000  --> 2147483648 --> 2^31
01111111111111111111111111111111  --> 2147483647 --> 2^31 -1
^ Sign bit
like image 57
Amit Deshpande Avatar answered Sep 21 '22 05:09

Amit Deshpande


The same rule does apply... 7 is 2^3 - 1. And yes, it's because of the 0. :)

In contrast, negatives go to -(2^31)

So there's 2^31 negative numbers, one 0, and 2^31-1 strict positives, which add to...

2^31 + 1 + 2^31 - 1 = 2 * 2^31 = 2^32
like image 24
Luchian Grigore Avatar answered Sep 20 '22 05:09

Luchian Grigore