Converter for integers and two's complement binary strings.
Two's complement converter
Step-by-step
Core idea
- Positive numbers: standard binary representation (with leading 0 as sign bit).
- Negative numbers: encoded in two's complement.
- Range (two’s complement, N bits): −2^(N−1) to +2^(N−1) − 1
Decimal → Two's complement (N bits)
A) Number is positive or 0
- Convert the decimal number to binary.
- Pad with leading zeros to N bits.
B) Number is negative
- Step 1: Write the absolute value in binary.
- Step 2: Pad to N bits.
- Step 3: Invert the bits (0↔1).
- Step 4: Add 1.
Two's complement → Decimal
Step 0: Check the sign
- The most significant bit (MSB) is the sign bit: 0 → positive, 1 → negative.
A) Leading bit is 0 (positive)
- Step 2: Convert binary to decimal normally.
B) Leading bit is 1 (negative)
- Step 1: Invert the bits
- Step 2: Add 1
- Step 3: The result is the magnitude, then add the minus sign
