What Is a Two's Complement Calculator?
Two's complement is the standard way computers represent signed integers in a fixed number of bits. This calculator takes a decimal number and an n-bit register width, then shows how that value is stored as a two's complement bit pattern, what unsigned value those bits represent, and how the bits are interpreted as a signed number. It works for both positive and negative inputs.
How to Use It
Enter the decimal value you want to encode and the number of bits (commonly 8, 16, 32). The calculator wraps the value into the n-bit register using modulo arithmetic, displays the binary representation, and decodes the signed interpretation. Negative inputs are automatically stored using their two's complement form.
The Formula Explained
To store a value \(x\) in \(n\) bits, compute the stored (unsigned) pattern as $$\text{stored} = \left(\left(x \bmod 2^{n}\right) + 2^{n}\right) \bmod 2^{n}$$ The two's complement (negation) of a stored value is $$\text{twos} = \left(2^{n} - \text{stored}\right) \bmod 2^{n}$$ To decode the signed meaning of an n-bit pattern: if the pattern is at least \(2^{n-1}\) the value is \(\text{pattern} - 2^{n}\) (negative), otherwise it is the pattern itself.
Worked Example
Encode -5 in 8 bits. Here \(2^8 = 256\), so $$\text{stored} = \left(\left(-5 \bmod 256\right) + 256\right) \bmod 256 = 251$$ In binary \(251 = 11111011\). Decoding 251: since \(251 \ge 2^7\) (128), the signed value is \(251 - 256 = -5\). The two's complement of 251 is \(\left(256 - 251\right) \bmod 256 = 5\), matching the magnitude.
FAQ
Why do negative numbers look like big binary patterns? The leading bits are 1s; in n-bit signed arithmetic a leading 1 marks a negative number, so 11111011 is -5, not 251.
What range fits in n bits? Signed values span \(-2^{n-1}\) to \(2^{n-1} - 1\). For 8 bits that is -128 to 127.
What if my number is too big? Values outside the register wrap around (overflow) by the modulo operation, exactly like real hardware.