Two's Complement Calculator

Calculate two's complement representation for signed integers.

Bit width:
Range: -128 to 127

How Two's Complement Works

For positive numbers, the binary representation is the same as unsigned. For negative numbers:

  1. Start with the absolute value in binary
  2. Invert all bits (one's complement)
  3. Add 1 to the result

Example: -5 in 8-bit two's complement:

  • 5 in binary: 00000101
  • Invert bits: 11111010
  • Add 1: 11111011

Code Examples

// JavaScript numbers are 64-bit, but bitwise ops use 32-bit
const num = -5;
const twosComp = num >>> 0;  // Convert to unsigned 32-bit
twosComp.toString(2);  // "11111111111111111111111111111011"

Frequently Asked Questions

What is two's complement?

Two's complement is the standard way computers represent signed integers. Positive numbers are normal binary. For negative numbers: invert all bits (one's complement) then add 1.

Why use two's complement?

Two's complement allows the same hardware to perform addition/subtraction on both positive and negative numbers. It also has only one representation of zero.

What's the range for N-bit two's complement?

For N bits: minimum is -2^(N-1), maximum is 2^(N-1)-1. 8-bit: -128 to 127. 16-bit: -32768 to 32767. 32-bit: about -2.1B to 2.1B.

Related Tools