How to use the twos complement converter
- Choose Decimal to bits or Bits to decimal, and the bit width (8, 16, 32 or 64).
- For decimal, enter a whole number, positive or negative. For bits, enter binary digits or hex starting with 0x.
- Read the binary, hex, signed and unsigned values, and the steps used.
- Copy or print the result.
Formula
A negative number -n in w bits is 2^w - n
To write it: flip every bit of n, then add 1
To read bits with a leading 1: signed value = unsigned value - 2^w
A signed w bit number ranges from -2^(w-1) to 2^(w-1) - 1. Values outside that range cannot be stored and are rejected.
-5 in 8 bits
The size 5 is 00000101. Flipping every bit gives 11111010, and adding 1 gives 11111011, which is 0xFB. Read as an unsigned number it is 251, and 251 - 256 = -5, which confirms it.
The edges at 8 bits are -128, written 10000000, and 127, written 01111111. The number 128 does not fit, because a signed 8 bit number stops at 127.
Why this system is used
Twos complement lets a computer use the same adding circuit for positive and negative whole numbers. The top bit tells the sign: 0 for zero or positive, 1 for negative. There is one zero, and the range has one more negative number than positive numbers, which is why -128 has no positive partner at 8 bits.
When you give bits instead of a decimal number, fewer digits than the width are padded with zeros on the left. So 101 at 8 bits is 00000101, which is 5, not -3. Write the leading ones if you mean a negative number, such as 11111101.
Overflow
This tool never wraps a number to make it fit. A decimal outside the range for the width is rejected with the range, and bits longer than the width are rejected too. In real programs, adding past the top of the range wraps around silently in many languages, which you can try with the bitwise calculator. See also the number base converter, the binary translator and the hex viewer. Everything runs in your browser.
Assumptions and limits
- The number is a whole number stored in the chosen width as twos complement.
- Input bits shorter than the width are padded with zeros on the left, not sign extended.
- Values outside the range for the width are rejected, not wrapped.
- 64 bit values are handled exactly with big integers.
Frequently asked questions
How do you write -5 in binary?
At 8 bits it is 11111011. Write 5 as 00000101, flip every bit to get 11111010, then add 1.
Why is there no +128 in 8 bit twos complement?
Eight bits give 256 patterns. Half have a leading 1 for negatives, which uses -1 to -128, and the other half cover 0 to 127.
What is the twos complement of 0?
It is all zeros. Flipping gives all ones and adding 1 carries out of the width, so the result is 0 again, which is why zero has just one form.
How do I read 11111111 as a number?
As a signed 8 bit number it is -1, and as an unsigned number it is 255. The tool shows both.