Advertisement

Two's complement calculator

Enter a whole number in decimal or binary and choose a bit width. Two's complement flips every bit and adds one, which negates the value.

Calculator

Numbers are stored without a sign unless a result is reported as signed.

The signed range is -(2ⁿ⁻¹) to +(2ⁿ⁻¹ - 1). There is only one zero.

Entered value in binary
00000101
Two's complement in binary
11111011
Entered value as signed decimal
5
Complement as signed decimal
-5
Complement as unsigned decimal
251

Advertisement

How this calculator works

Two's complement is the standard way computers store signed integers. A non-negative value is written in ordinary binary, padded to the chosen width. A negative value is written by flipping every bit of its magnitude and then adding one, which is the same as subtracting the magnitude from 2ⁿ. The leading bit is still a sign bit: 0 for non-negative and 1 for negative. Unlike one's complement, there is only one zero, so the negative range gains one extra value. The cost is that negating the minimum value overflows, because its positive counterpart is one step outside the representable range.

Formula

For an n-bit width, a negative value x is stored as 2ⁿ + x. The two's complement of a stored pattern S is (2ⁿ - S) mod 2ⁿ, which equals flipping all bits and adding one. The signed range is -2ⁿ⁻¹ to 2ⁿ⁻¹ - 1.

Worked example

In 8 bits, 5 is 00000101 and its two's complement is 11111011, which reads as -5. Flipping 11111011 back and adding one returns 00000101, or 5. In 4 bits, 1000 reads as -8, and its two's complement is also 1000, because +8 cannot be represented in four signed bits.

Advertisement

Frequently asked questions

Why add one after flipping the bits?

Flipping alone gives one's complement, which has two zeros. Adding one shifts the negative values down by one step, removes the duplicate zero and frees a pattern for the most negative value. It also makes addition work without special cases.

Why does the most negative value negate to itself?

In 8 bits the range is -128 to 127. Negating -128 would need +128, which does not fit in a signed 8-bit number. The stored pattern 10000000 is produced again, so the calculator reports -128 and the edge case is expected, not a bug.

What is the signed range for n bits?

It runs from -2ⁿ⁻¹ to 2ⁿ⁻¹ - 1. For 8 bits that is -128 to 127; for 16 bits it is -32768 to 32767; for 32 bits it is -2147483648 to 2147483647.

How do I read a binary pattern as a signed number?

If the leading bit is 0, read it as ordinary unsigned binary. If the leading bit is 1, subtract 2ⁿ from the unsigned value. For example, 11111011 is 251 unsigned in 8 bits, and 251 - 256 = -5 signed.

Sources

Advertisement