DEV Community

João Paulo Martins Silva
João Paulo Martins Silva

Posted on

Revisiting Two's complement: A demonstration using Java

public class Main {
    public static void main(String[] args) {
        int number = 1;
        int invertedNumber = ~number; // Invert bits using the ~ operator
        int invertedNumberPlusOne = invertedNumber + 1;
        System.out.println("Number = " + number + " Binary value: " + Integer.toBinaryString(number));
        System.out.println("Inverted number = " + invertedNumber + " Binary value: " + Integer.toBinaryString(invertedNumber));
        System.out.println("Negative number = " + invertedNumberPlusOne + " Binary value: " + Integer.toBinaryString(invertedNumberPlusOne));
    }
}
Enter fullscreen mode Exit fullscreen mode

Output:

Number = 1 Binary value: 1
Inverted number = -2 Binary value: 11111111111111111111111111111110
Negative number = -1 Binary value: 11111111111111111111111111111111
Enter fullscreen mode Exit fullscreen mode

At first glance, this code might seem nonsensical, but it demonstrates how computers represent negative numbers in binary using two's complement. In this example, the number 1 is converted to -1 by inverting its bits and adding 1.

How Does Two's Complement Work?

Two's complement is a mathematical trick for efficiently representing negative numbers in binary. The process involves:

  1. Inverting the bits of the binary representation of the number.
  2. Adding 1 to the inverted result.

But why does this work? It’s tied to how binary subtraction operates. When transforming a number into its negative counterpart, you’re essentially subtracting the number from 0. For example:


Explanation Image 1


Similar to decimal subtraction, binary subtraction follows the borrowing rule (reference here). Notice how subtracting a number from 0 involves flipping its bits and then adding 1.

In most systems, binary numbers are stored in fixed-width variables (e.g., 8 bits). Any extra bits from the computation are simply discarded, which means subtracting 01001011 from 100000000 (1 followed by 8 zeros) is functionally identical to subtracting it from 0.

Here’s what happens when you carry out this subtraction:


Explanation Image 2


By splitting the computation into two steps:

  1. Flip the bits: 11111111.
  2. Add 1: 1 + 11111111 = 100000000.

The result is the same as performing a direct subtraction.


Explanation Image 3


In essence, subtracting a binary number ( A ) from an all-ones number is equivalent to inverting the bits of ( A ). The Java program leverages this trick to efficiently compute the negative of a number using two's complement.

Key Takeaway:

The Java program illustrates a clever use of two's complement for converting a binary number into its negative counterpart.

Source: Cornell University: Two's Complement Notes

Top comments (0)