Two's complement converter

A signed integer to n-bit two's complement and back, with invert and add one, and the range check.

How it works

Two’s complement is how computers store negative integers. With $n$ bits, a number $x$ that is not negative is written in plain binary, and a negative $x$ is written as $2^n + x$. In 8 bits, $-42$ becomes $256 - 42 = 214$, that is 11010110. Equivalently, the top bit is worth $-2^{n-1}$ instead of $+2^{n-1}$, so 8 bits cover $-128$ to $127$.

The quick way to negate: invert every bit and add one. That works because inverting $x$ gives $(2^n - 1) - x$. Reading a pattern back is the same: if the top bit is 1, invert and add one to get the absolute value.

The point is that the hardware needs no special case for signs: addition, subtraction and multiplication are simply done modulo $2^n$, the same circuits as for unsigned numbers. Overflow is what happens when the true result leaves the range, as when $127 + 1$ wraps around to $-128$.

Everything is calculated in your browser. Nothing you type leaves your device.