Representation of integers in the JVM

JVM integers include byte, short, int, and long, which can be divided into 8, 16, 32, and 64 bit signed integers. Integers are represented by complement in computers.

The original code

The source code is the binary representation of the sign bit + number.

Take int, where the first bit is a sign bit, 0 is an integer, and 1 is a negative number. The remaining 31 bits are binary values of numbers.

The source code of 10 is 00000000 00000000 00000000 00001010

– the source code of 10 is 10000000 00000000 00000000 00001010

Radix-minus-one complement

The inverse code is on the basis of the original code, the symbol bit is unchanged, the rest of the bits are reversed.

The inverse of 10 is 01111111 11111111 111111 11110101

The inverse of -10 is 11111111 11111111 11111111 11110101

complement

The complement of a positive number is the original code, and the complement of a negative number is the inverse plus 1

The complement of 10 is 00000000 00000000 00000000 00001010. The complement of 10 is 11111111 11111111 11110110Copy the code

The benefits of using complement

The use of complement as the actual storage in a computer has at least two advantages over source code.

Advantage one: unified representation of the number 0

0 is neither an integer nor a negative number, and the sign bit is difficult to determine if it is expressed in source code.

If you use the complement, you get the same result whether you make 0 positive or negative

When 0 is positive, the complement is the original code itself: 00000000 00000000 00000000 00000000 00000000

When the zero bit is negative, the complement is the inverse plus one

The source code of negative 0 is 10000000 00000000 00000000 00000000

The inverse code is 11111111 11111111 11111111

The complement is the inverse plus 1, and the result is: 00000000 00000000 00000000 00000000 00000000

Benefit two: simplify integer addition and subtraction calculation

With complement code, subtraction calculation can be regarded as addition calculation to achieve complete unification of addition and subtraction. Take 8-byte as an example

So let’s do minus 6 plus 5.

  • -6 Complement: 1111 1010
  • 5 Complement: 0000 0101
  • You add them up: 1111, 1111
  • Sign bit 1 means negative number, inverse derivation inverse is equal to complement plus 1,
  • The inverse code is 1111, 1110
  • The original code is 1000 0001
  • The result is: -1.

Let’s do the 4 + 6 process.

  • The complement of 4:0000 0100
  • The complement of 6:0000 0110
  • Add them up: 0000, 1010
  • A sign bit of 0 indicates an integer, and the complement is equal to the source code itself
  • The original code is 0000 1010
  • The result is: 10