0

I'm wondering why java int type (32 bit signed) has valid value in range -2,147,483,648 to 2,147,483,647 but not in (-2,147,483,648 to 2,147,483,648)?

logbasex
  • 1,688
  • 1
  • 16
  • 22
  • 9
    Because 0 is a number as well. If you count all of them you will see that that's how many fit in 32 bits. – Amongalen Feb 21 '20 at 14:49
  • 3
    [Two's Complement](https://en.wikipedia.org/wiki/Two%27s_complement) – BeUndead Feb 21 '20 at 14:52
  • 2
    Related: [What is “2's Complement”?](//stackoverflow.com/q/1049722) – 001 Feb 21 '20 at 14:52
  • This means out of memory to allocate and represent 2,147,483,64? Right? – logbasex Feb 21 '20 at 14:52
  • no, it just means that it requires more than 32 bits (assuming two's complement representation of 2_147_483_648) – user85421 Feb 21 '20 at 14:53
  • Assume a 2 bit integer. 00 = 0, 01 = 1; 10 = -2, 11 = -1. With two's complement, the absolute value of the most negative number is one larger than the most positive number. – NomadMaker Feb 21 '20 at 15:57

1 Answers1

4

The primary representation of numbers in modern computers is some form of binary representation. It consists of a fixed number of bits that take the values 0 or 1. In Java, an int is specified to use a binary representation with 32 bits.

A 32 bit binary representation can have 2^32 states. (This is a mathematical fact. It can be proven from first principles.)

Consider the mathematical integers from -2^31 to +2^31:

  • There are 2^31 numbers in the range 1 to 2^31 (inclusive)

  • There are 2^31 numbers in the range -1 down to -(2^31) (inclusive)

  • The value zero is not in either of the above ranges.

So counting the numbers from -2^31 to +2^31, we get a total of 2^31 + 2^31 + 1 values. That is 2^32 + 1 which is more values than can be represented in 2^32 states.

What you are suggesting is not mathematically possible.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216