Beetwise

How two’s complement works

Two’s complement stores a negative value in a fixed number of bits.

To get the negative form, invert every bit of the magnitude and then add 1.

In 8 bits, the register holds -6 as 11111010. The same bits give 250 for an unsigned value.

Try it

The bits of -6 in an 8-bit signed register. Select a bit to change it. Change the bit width or the signed mode to see the effect.

Name or expression
ID0
Binary
0b
Hex
0x
Decimal
ASCII
·
Shift
Sign
Bits
Endian
7
6
5
4
3
2
1
0

Worked example

Convert -6 into an 8-bit signed value:

  1. Write the magnitude 6 in binary: 00000110.
  2. Invert every bit: 11111001.
  3. Add 1: 11111010.
  4. The result is 250 as an unsigned value and -6 as a signed value.

Where this is used

A processor uses one adder circuit for addition and for subtraction.

Two’s complement makes this possible, because a subtraction becomes an addition of the negative form.

This is the reason almost all hardware stores signed values in this form.

Points to note

  • The top bit is not a minus sign. The top bit is part of the value.
  • The range is not symmetric. An 8-bit signed value holds -128 to 127, because 0 uses one of the positive codes.
  • A change of the signed mode does not change the bits. The same bits then give a different value.
  • A change of the bit width does change the value. The value 300 in 8 bits becomes 44, because the register drops the higher bits.

The full tool

The full editor holds many values at the same time. It also evaluates expressions across them, and it reads live values from a serial port.

Open the full editor

Questions

What is -1 in binary?
In 8 bits, -1 is 11111111. All bits have the value 1. The same bits give 255 for an unsigned value.
Why not use a sign bit and a magnitude?
A sign bit gives two codes for zero and needs a second circuit for subtraction. Two’s complement avoids both problems.
How do I convert back to a decimal value?
Invert every bit and add 1. Then read the result as a magnitude and put a minus sign in front of it.