Jeel Shah
Jeel Shah

Reputation: 3334

Why do integers in Java integer not use all the 32 or 64 bits?

I was looking into 32-bit and 64-bit. I noticed that the range of integer values that can stored in 32 bits is ±4,294,967,295 but the Java int is also 32-bit (If I am not mistaken) and it stores values up to ±2 147 483 648. Same thing for long, it stores values from 0 to ±2^63 but 64-bit stores ±2^64 values. How come these values are different?

Upvotes: 2

Views: 2224

Answers (3)

seh
seh

Reputation: 15269

Integers in Java are signed, so one bit is reserved to represent whether the number is positive or negative. The representation is called "two's complement notation." With this approach, the maximum positive value represented by n bits is given by

(2 ^ (n - 1)) - 1

and the corresponding minimum negative value is given by

-(2 ^ (n - 1))

The "off-by-one" aspect to the positive and negative bounds is due to zero. Zero takes up a slot, leaving an even number of negative numbers and an odd number of positive numbers. If you picture the represented values as marks on a circle—like hours on a clock face—you'll see that zero belongs more to the positive range than the negative range. In other words, if you count zero as sort of positive, you'll find more symmetry in the positive and negative value ranges.

To learn this representation, start small. Take, say, three bits and write out all the numbers that can be represented:

  • 0
  • 1
  • 2
  • 3
  • -4
  • -3
  • -2
  • -1

Can you write the three-bit sequence that defines each of those numbers? Once you understand how to do that, try it with one more bit. From there, you imagine how it extends up to 32 or 64 bits.

That sequence forms a "wheel," where each is formed by adding one to the previous, with noted wraparound from 3 to -4. That wraparound effect (which can also occur with subtraction) is called "modulo arithemetic."

Upvotes: 7

The Nail
The Nail

Reputation: 8490

That's because Java ints are signed, so you need one bit for the sign.

Upvotes: 0

A.H.
A.H.

Reputation: 66263

In 32 bit you can store 2^32 values. If you call these values 0 to 4294967295 or -2147483648 to +2147483647 is up to you. This difference is called "signed type" versus "unsigned type". The language Java supports only signed types for int. Other languages have different types for an unsigned 32bit type.

NO laguage will have a 32bit type for ±4294967295, because the "-" part would require another bit.

Upvotes: 2

Related Questions