What is two’s complement?
Two’s complement is the standard way computers store signed integers — numbers that can be positive or negative — using a fixed number of bits. Instead of setting aside a separate symbol for the minus sign, the negative numbers are encoded so that ordinary binary addition just works, with no special handling for the sign. Almost every modern CPU represents integers this way.
This calculator takes a decimal integer and a bit width (8, 16, or 32 bits) and shows its two’s complement pattern in both binary and hexadecimal.
How does it work?
For a chosen width of bits, each value is stored as an unsigned bit pattern:
- If the number is non-negative, its pattern is simply the binary of , padded with leading zeros to bits.
- If the number is negative, its pattern is the binary of .
Because is negative in the second case, is a positive value smaller than , so it always fits in bits. The most significant (leftmost) bit ends up being for every negative number and for every non-negative one — that bit acts as the sign.
Formula
The result is then written with exactly binary digits (or hexadecimal digits).
Worked examples
Example 1: a positive number
Encode in bits. Since , the pattern is just in binary, padded to eight digits:
Example 2: negative one
Encode in bits. Since , compute :
Negative one is always an unbroken row of ones, whatever the width.
Example 3: negative five
Encode in bits. Compute :
Reference table (8-bit)
| Decimal | Two’s complement binary | Hex |
|---|---|---|
| 5 | 00000101 | 0x05 |
| 0 | 00000000 | 0x00 |
| -1 | 11111111 | 0xFF |
| -5 | 11111011 | 0xFB |
| 127 | 01111111 | 0x7F |
| -128 | 10000000 | 0x80 |
Notes
- An -bit signed integer covers the range to ; bits covers to ; bits covers roughly billion. Values outside the chosen range wrap around modulo .
- The leading bit is the sign: marks a non-negative number and marks a negative one.
- To convert an ordinary non-negative number to binary without a sign bit, use the decimal to binary converter, or the general number system converter for other bases.
FAQ
What is -1 in two’s complement?
In any width it is all ones: (0xFF) for 8 bits, (0xFFFF) for 16 bits, and so on.
How do I get the two’s complement of a negative number by hand?
Write the size of the number in binary, flip every bit, then add one. For in 8 bits: is , flipping gives , and adding one gives — the same result as .
Why does the bit width matter?
The width fixes how many bits the pattern occupies and therefore the range of numbers you can store. The same decimal value produces a longer string of leading zeros or ones as the width grows.