Developer Tools
Two's complement.
Convert signed decimal to two's complement binary and hex, decode a bit pattern back to a signed number, or add and subtract with an overflow flag. 4, 8, 16, 32 and 64 bits. Runs in your browser.
Input
Result
Enter a value, then press Calculate.
How it works
- Range: with n bits you can store -2n-1 to 2n-1-1 (8-bit: -128 to 127). The leading bit is 1 for negative numbers.
- Negate: write the magnitude in binary, invert every bit, add one, and discard any carry out of the top bit. Example: 5 = 00000101, inverted 11111010, plus one = 11111011 = -5.
- Decode: if the leading bit is 1, invert and add one to get the magnitude, or subtract 2n from the unsigned value.
- Overflow: the exact result of an add or subtract does not fit the range. The tool also shows the wrapped n-bit result and whether a carry left the top bit (carry-out is a separate thing from signed overflow). Subtraction is done as A + (invert B + 1).
- Precision: uses BigInt, so 64-bit values are exact. Nothing is sent anywhere.
Sources: Wikipedia, Two's complement; Cornell notes on two's complement. Related: Binary Converter.