StringMash.com

Two's complement calculator

Signed binary, with the invert-and-add-one working shown.

Conversion
2 characters
Updates as you type
Binary1111 1011
HexFB
Range-128 to 127

Show the steps
  1. Start from 5 in binary, padded to 8 bits: 0000 0101.
  2. Invert every bit: 1111 1010.
  3. Add 1: 1111 1011.
  4. The leading 1 marks a negative number. As a check, 1111 1011 read as an unsigned number is 251, and 251 − 2^8 = -5.

Using it

Type a whole number, negative or not, and pick how many bits to use. The output is the two's complement pattern in groups of four, with the hex and the range that width can hold in the rows. The steps show the textbook method: write the size in binary, invert every bit, add 1.

Swap the boxes to read a pattern back. Type the bits, or hex starting 0x, and the leading bit decides the sign.

How it works

In two's complement a pattern of n bits whose leading bit is 1 stands for its unsigned value minus 2ⁿ. In 8 bits, 1111 1011 is 251 unsigned, and 251 − 256 = −5. Inverting the bits and adding 1 gets to the same pattern by hand, and it works both ways: do it again to 1111 1011 and you get back 0000 0101.

The point of the system is that ordinary binary addition just works. Add 5 and −5 as plain 8-bit numbers, 0000 0101 + 1111 1011, and the carry falls off the end to leave 0000 0000. A processor needs no separate circuit for subtraction, and there is only one zero.

Ranges by width

BitsSmallestLargest
4-87
8-128127
16-32,76832,767
32-2,147,483,6482,147,483,647
64-9,223,372,036,854,775,8089,223,372,036,854,775,807

One's complement and sign-magnitude

Two older schemes are worth knowing for exams. Sign-magnitude uses the first bit as a minus sign and the rest as the size, so −5 in 8 bits is 1000 0101. One's complement just inverts every bit, so −5 is 1111 1010. Both have two zeros, a positive and a negative one, and both need extra care when adding, which is why almost every modern computer uses two's complement.

Questions

What is −1 in two's complement?

All ones: 1111 1111 in 8 bits, FFFF FFFF in 32.

Why can 8 bits hold −128 but only +127?

Zero takes one of the patterns that start with 0, so the positive side has one fewer. 1000 0000 is −128, and it has no positive partner.

How do I make a number wider?

Copy the leading bit into the new positions. −5 in 8 bits is 1111 1011; in 16 it's 1111 1111 1111 1011. This is called sign extension.

Sources

Added . What's new