Programming Search⌘K

Conceptcore

Two's complement

Also called two's complement, twos complement, 2's complement, invert and add one, most negative number, sign extension, signed binary.

Two's complement stores a negative integer as the bits of its magnitude inverted plus one. The same adder works for signed and unsigned values, and the range has one more negative value.

Applies to
core-languages

Idea

Two's complement is the usual way to store signed integers in a fixed number of bits. A value that is 0 or more has its usual binary form. For a negative value, "negative numbers are represented by taking the bit complement of their magnitude and then adding one (−6 is 1010)."1 In 4 bits, 6 is 0110, the inverted bits are 1001, and adding 1 gives 1010.

BITS = 8
MASK = (1 << BITS) - 1


def value(bits):
    """Read 8 bits as two's complement: the top bit is worth -128."""
    return bits - (1 << BITS) if bits & 0x80 else bits


def negate(bits):
    return (~bits + 1) & MASK  # invert every bit, then add 1


six = 0b00000110
rows = [
    ("6", six),
    ("inverted", ~six & MASK),
    ("plus 1", negate(six)),
    ("again", negate(negate(six))),
    ("negate 0", negate(0)),
    ("negate -128", negate(0x80)),
]
for label, bits in rows:
    print(f"{label + ':':<13}{bits:08b} = {value(bits)}")
Output
6:           00000110 = 6
inverted:    11111001 = -7
plus 1:      11111010 = -6
again:       00000110 = 6
negate 0:    00000000 = 0
negate -128: 10000000 = -128

The same steps also turn -6 back into 6. Zero has one form, because the carry out of the top bit is dropped. The most negative value, -128 in 8 bits, is its own negation, because +128 does not fit.

How it works

Bit weights. In two's complement, "The weight of each bit is a power of two, except for the most significant bit, whose weight is the negative of the corresponding power of two."1 In 8 bits, the top bit is worth -128 and the others are worth 64, 32, 16, 8, 4, 2 and 1. So 11111010 is -128 + 64 + 32 + 16 + 8 + 2 = -6. The top bit also tells the sign: it is 1 for each negative value.

Negation. Inverting each bit of x gives -x - 1, as the row for the inverted bits shows: the bits of 6 inverted are -7. So inverting and adding 1 gives -x. The Java Language Specification states this rule for all integer values: -x equals (~x)+12. For JavaScript numbers, "Bitwise NOTing any 32-bit integer x yields -(x + 1)"3.

One adder for both signs. Addition, subtraction and multiplication give the same bits for signed and unsigned operands. Wikipedia says that "the same arithmetic implementations can be used on signed as well as unsigned integers" and that they "differ only in the integer overflow situations"1. The machine has one add instruction, and the program decides how to read the result:

def value(bits):
    return bits - 256 if bits & 0x80 else bits


for a, b in [(0b11111010, 0b00001010), (0b11111111, 0b11111111), (0b01111111, 0b00000001)]:
    s = (a + b) & 0xFF
    print(f"{a:08b} + {b:08b} = {s:08b}  unsigned {a} + {b} = {s}  signed {value(a)} + {value(b)} = {value(s)}")
Output
11111010 + 00001010 = 00000100  unsigned 250 + 10 = 4  signed -6 + 10 = 4
11111111 + 11111111 = 11111110  unsigned 255 + 255 = 254  signed -1 + -1 = -2
01111111 + 00000001 = 10000000  unsigned 127 + 1 = 128  signed 127 + 1 = -128

The first two sums are right as signed values, and they overflow as unsigned values. The last sum is right as an unsigned value and overflows as a signed value: two positive operands give a negative result.

The range is not symmetric. Two's complement "has only one representation for zero, with room for one extra negative number (the range of a 4-bit number is −8 to +7)."1 With N bits, the range is -2ᴺ⁻¹ to 2ᴺ⁻¹ - 1. So the most negative value has no positive partner: "The two's complement of the most negative number representable (e.g. a one as the most-significant bit and all other bits zero) is itself."1 Each language handles this case in its own way. Java says that "negation of the maximum negative int or long results in that same maximum negative number. Overflow occurs in this case, but no exception is thrown."2 In C, unary minus "invokes undefined behavior due to signed integer overflow when applied to INT_MIN, LONG_MIN, or LLONG_MIN"4. Rust's checked_neg computes the negation, "returning None if self == MIN"5. C# wraps by default, and for an overflow in a checked context, "a System.OverflowException is thrown."6

Sign extension. To store a value in more bits, "the most-significant bit must be repeated in all the extra bits."1 So -6 in 8 bits, 11111010, becomes 1111111111111010 in 16 bits. A right shift of a signed value also copies the top bit, so the sign does not change.

Why the standards require it. For a long time, C and C++ also allowed ones' complement and sign-magnitude. The proposal P0907 starts: "There is One True Representation for signed integers, and that representation is two’s complement."7 It notes that "None of [MSVC], [GCC], and [LLVM] support other representations."7 For C++, two's complement became "the only representation allowed by the standard" as of C++208, and C23 made the same change for C9. C++20 also defined the conversion of a value that does not fit into a signed type: the result is the value modulo 2ᴺ10. P0907 did not make signed overflow defined: "If a signed operation would naturally produce a value that is not within the range of the result type, the behavior is undefined."7 Java defines its integral types as "signed two's-complement integers"11 from the start, and the Go specification says: "The value of an n-bit integer is n bits wide and represented using two's complement arithmetic."12

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript has the 32-bit bitwise operators and BigInt.asIntN of JavaScript, but no example file exists.
GoNative
RustNative
KotlinNativeKotlin's Byte, Short, Int and Long are two's complement types, as in Java. No example file exists because kotlinc is not installed.
SQLDoes not applySQL integer types have ranges, but SQL has no operators that show the bits of a value.
BashNativeBash arithmetic in $(( )) uses the signed integers of the machine, so $(( ~5 )) is -6. No example file exists.
PowerShellNativePowerShell uses the .NET signed types, such as [int] and [long]. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML has no numbers.
CSSDoes not applyCSS has integer values, such as z-index, but no integer types with a width.
Regular expressionsDoes not applyA pattern matches digits as text but has no integer types.
Language Verdict Two's complement in the language
Python native int has no width; bit operations act as if it had infinite sign bits
JavaScript native bit operators work on 32-bit two's complement values; BigInt.asIntN
TypeScript native as JavaScript
Java native byte, short, int, long are two's complement by definition
Kotlin native Byte, Short, Int, Long as in Java
C# native sbyte, short, int, long; checked and unchecked
Go native each signed type, by the specification
Rust native each signed type; wrapping_neg, checked_neg
C native required since C23; -INT_MIN is undefined
C++ native required since C++20
Bash native $(( )) arithmetic on signed integers
PowerShell native the .NET signed types
SQL n/a the database stores the value; SQL does not show the bits
Regex n/a no numbers
HTML n/a no numbers
CSS n/a no integer types with a width

Each general-purpose language uses two's complement for its fixed-width signed types. Python is a special case. Its int has no width, but "The result of bitwise operations is calculated as though carried out in two’s complement with an infinite number of sign bits."13 So ~5 is -6 in Python, as it is in C.

The example files show the same facts in each language: -x equals ~x + 1, the bits of -1 are all ones, the negation of the most negative value overflows, and a widening conversion copies the sign bit.

PythonGitHub
print("~5:", ~5)
print("-6 & 0xFF:", f"{-6 & 0xFF:08b}")
print("(-6).to_bytes(2, signed=True):", (-6).to_bytes(2, "big", signed=True).hex())
print("from_bytes(b'\\xfa', signed=True):", int.from_bytes(b"\xfa", "big", signed=True))
print("-(-128):", -(-128))
Output
~5: -6
-6 & 0xFF: 11111010
(-6).to_bytes(2, signed=True): fffa
from_bytes(b'\xfa', signed=True): -6
-(-128): 128
  • Verdict: native. Python's int has no width, but bitwise operations act as if it were two's complement with an infinite number of sign bits.
  • x & 0xFF gives the low 8 bits of the two's complement form. to_bytes with signed=True writes the form in a fixed number of bytes, and the 2-byte form of -6 shows the sign extension.
  • -(-128) is 128, because Python integers do not overflow.
#include <bit>
#include <climits>
#include <cstdint>
#include <iostream>

int main() {
    std::int8_t x = -6;
    std::cout << "bits of -6: " << std::hex << +std::bit_cast<std::uint8_t>(x) << '\n';
    std::cout << "static_cast<std::int8_t>(250): " << std::dec
              << +static_cast<std::int8_t>(250) << '\n';
    int y = INT_MIN;
    std::cout << "-(INT_MIN + 1): " << -(y + 1) << '\n';
    std::cout << "INT_MIN as unsigned: " << static_cast<unsigned int>(y) << '\n';
}
Output
bits of -6: fa
static_cast<std::int8_t>(250): -6
-(INT_MIN + 1): 2147483647
INT_MIN as unsigned: 2147483648
  • Verdict: native. C++20 allows only two's complement for signed integers.
  • std::bit_cast shows the bits of a signed value as an unsigned value of the same size.
  • Since C++20, a conversion to a signed type that cannot hold the value gives the value modulo 2ᴺ, so 250 becomes -6.
  • -INT_MIN is still undefined behavior. -(INT_MIN + 1) is the largest int.
JavaGitHub
public class Main {
  public static void main(String[] args) {
    int x = 6;
    System.out.println("-x == ~x + 1: " + (-x == ~x + 1 ? "yes" : "no"));
    System.out.println("-1 in hex: " + Integer.toHexString(-1));
    System.out.println("-Integer.MIN_VALUE: " + -Integer.MIN_VALUE);
    System.out.println("Math.abs(Integer.MIN_VALUE): " + Math.abs(Integer.MIN_VALUE));
    try {
      Math.negateExact(Integer.MIN_VALUE);
    } catch (ArithmeticException e) {
      System.out.println("Math.negateExact(Integer.MIN_VALUE): ArithmeticException");
    }

    byte b = (byte) 0xFA;
    System.out.println("(int) b: " + (int) b);
    System.out.println("b & 0xFF: " + (b & 0xFF));
  }
}
Output
-x == ~x + 1: yes
-1 in hex: ffffffff
-Integer.MIN_VALUE: -2147483648
Math.abs(Integer.MIN_VALUE): -2147483648
Math.negateExact(Integer.MIN_VALUE): ArithmeticException
(int) b: -6
b & 0xFF: 250
  • Verdict: native. The Java Language Specification defines byte, short, int and long as two's complement integers.
  • The negation of Integer.MIN_VALUE is the same value, with no exception. Math.negateExact and Math.absExact throw an ArithmeticException instead.
  • A cast from byte to int copies the sign bit. The mask & 0xFF keeps only the low 8 bits.
#include <limits.h>
#include <stdint.h>
#include <stdio.h>

int main(void) {
    int x = 6;
    printf("-x == ~x + 1: %s\n", -x == ~x + 1 ? "yes" : "no");
    printf("-1 in hex: %x\n", (unsigned int) -1);

    int8_t small = -6;
    int16_t wide = small;
    printf("int8_t -6 as int16_t: %04x\n", (unsigned int) (uint16_t) wide);

    int y = INT_MIN;
    if (y == INT_MIN) {
        printf("-INT_MIN does not fit; INT_MAX is %d\n", INT_MAX);
    } else {
        printf("-y: %d\n", -y);
    }
    return 0;
}
Output
-x == ~x + 1: yes
-1 in hex: ffffffff
int8_t -6 as int16_t: fffa
-INT_MIN does not fit; INT_MAX is 2147483647
  • Verdict: native. C23 allows only two's complement for signed integers, and the compilers in use did so before.
  • The conversion of int8_t to int16_t keeps the value -6, so the new high bits are copies of the sign bit.
  • -INT_MIN is undefined behavior, so the program tests for INT_MIN before the negation.
using System;

int x = 6;
Console.WriteLine($"-x == ~x + 1: {(-x == ~x + 1 ? "yes" : "no")}");
Console.WriteLine($"-1 in hex: {-1:x8}");
Console.WriteLine($"(sbyte)-6 widened to short: {(short)(sbyte)-6:x4}");

int min = int.MinValue;
Console.WriteLine($"unchecked(-min): {unchecked(-min)}");
try
{
    Console.WriteLine(checked(-min));
}
catch (OverflowException)
{
    Console.WriteLine("checked(-min): OverflowException");
}
Output
-x == ~x + 1: yes
-1 in hex: ffffffff
(sbyte)-6 widened to short: fffa
unchecked(-min): -2147483648
checked(-min): OverflowException
  • Verdict: native. The signed types sbyte, short, int and long use two's complement.
  • The format x8 prints the bits of a negative value in hexadecimal. The widened short has copies of the sign bit in its high bits.
  • In the default unchecked context, the negation of int.MinValue is the same value. In a checked context, it throws OverflowException.
JavaScriptGitHub
console.log("~5:", ~5);
console.log("-6 >>> 0 in hex:", (-6 >>> 0).toString(16));
console.log("-(2 ** 31) | 0:", -(2 ** 31) | 0);
console.log("2 ** 31 | 0:", 2 ** 31 | 0);
console.log("BigInt.asIntN(8, 250n):", BigInt.asIntN(8, 250n));
Output
~5: -6
-6 >>> 0 in hex: fffffffa
-(2 ** 31) | 0: -2147483648
2 ** 31 | 0: -2147483648
BigInt.asIntN(8, 250n): -6n
  • Verdict: native. The bitwise operators convert a number to a 32-bit two's complement integer, so ~x is -(x + 1).
  • x | 0 converts to a signed 32-bit value. 2³¹ does not fit, so it becomes the most negative 32-bit value.
  • BigInt.asIntN(8, x) reads the low 8 bits of x as a two's complement value.
package main

import (
	"fmt"
	"math"
)

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	x := int32(6)
	fmt.Println("-x == ^x + 1:", yesNo(-x == ^x+1))
	v := int8(-6)
	fmt.Printf("bits of -6 as int8: %08b\n", uint8(v))
	fmt.Printf("int8(-6) widened to int16: %016b\n", uint16(int16(v)))

	m := int32(math.MinInt32)
	fmt.Println("-m:", -m)
	fmt.Println("m / -1:", m/-1)
}
Output
-x == ^x + 1: yes
bits of -6 as int8: 11111010
int8(-6) widened to int16: 1111111111111010
-m: -2147483648
m / -1: -2147483648
  • Verdict: native. The Go specification says that each n-bit integer is represented with two's complement arithmetic.
  • Go writes bitwise NOT as the unary operator ^.
  • Signed overflow wraps in Go, so the negation of the most negative int32 is the same value, and the division by -1 gives the same value too. There is no panic.
RustGitHub
fn main() {
    let x: i32 = 6;
    println!("-x == !x + 1: {}", if -x == !x + 1 { "yes" } else { "no" });
    println!("bits of -6i8: {:08b}", -6i8);
    println!("-6i8 as i16: {:016b}", -6i8 as i16);

    println!("i32::MIN.checked_neg(): {:?}", i32::MIN.checked_neg());
    println!("i32::MIN.wrapping_neg(): {}", i32::MIN.wrapping_neg());
    println!("i32::MIN.overflowing_neg(): {:?}", i32::MIN.overflowing_neg());
}
Output
-x == !x + 1: yes
bits of -6i8: 11111010
-6i8 as i16: 1111111111111010
i32::MIN.checked_neg(): None
i32::MIN.wrapping_neg(): -2147483648
i32::MIN.overflowing_neg(): (-2147483648, true)
  • Verdict: native. Rust's signed types i8 to i128 and isize use two's complement.
  • Rust writes bitwise NOT as !. The format {:b} of a signed value prints its two's complement bits.
  • checked_neg, wrapping_neg and overflowing_neg say what to do with the most negative value. A plain -x on that value panics in a debug build.
  • Ones' complement and sign-magnitude. These older forms have two zeros and need different adders for signed and unsigned values. See Ones' complement and sign-magnitude.
  • Offset binary. A value is stored as x + K, so the bits sort in the order of the values. The exponent of an IEEE 754 float uses this form. See IEEE 754.
  • Two's complement as arithmetic modulo 2ᴺ. An N-bit two's complement value -x has the same bits as the unsigned value 2ᴺ - x. This is why one adder works for both. See Signed and unsigned integers.
  • Overflow rules. Two's complement tells what bits a result has. It does not tell whether an overflow wraps, traps or is undefined. See Integer overflow behaviour.

Pitfalls

  • Negating the most negative value. -x, abs(x) and x / -1 fail for the most negative value. Java's Math.abs notes that for Integer.MIN_VALUE, "the most negative representable int value, the result is that same value, which is negative."14 In C, the same operation is undefined behavior4. Test for the minimum first, or use Math.absExact, checked_neg or a wider type.
  • Thinking that the C standard defines overflow. C23 and C++20 fix the representation, but signed overflow is still undefined behavior7. A program that relies on wraparound must use unsigned types or the wrapping functions of its compiler.
  • Losing the sign when widening. A value read from a byte with an unsigned type and then stored in a wider signed type is not sign-extended. The Java example shows that (int) b copies the sign of a byte, and b & 0xFF gives 0 to 255. Choose the extension that matches the meaning of the data.
  • Comparing bits as unsigned values. The bits of a negative value are larger than the bits of each positive value when they are read as unsigned. Sorting raw bytes or words gives the negative values last.

Cost

Two's complement makes signed arithmetic cost the same as unsigned arithmetic. The hardware has one adder, and subtraction is addition of the negation. Wikipedia notes that "the advantage of using two's complement is the elimination of examining the signs of the operands to determine whether addition or subtraction is needed."1 Sign extension can be one instruction: "Some processors do this in a single instruction; on other processors, a conditional must be used followed by code to set the relevant bits or bytes."1

History

"The method of complements had long been used to perform subtraction in decimal adding machines and mechanical calculators."1 John von Neumann suggested two's complement in his First Draft of a Report on the EDVAC of 1945, and the EDSAC of 1949 used it1. Many early computers used ones' complement or sign-magnitude instead. The IBM System/360 of 1964 "made two's complement the most widely used binary representation in the computer industry."1 The PDP-8 of 1965, the Data General Nova of 1969 and the PDP-11 of 1970 also used it1.

JF Bastien's proposal P0907 of 2018 made two's complement the only signed representation in C++2078, and C23 followed9.

References

  1. Two's complement, Wikipedia, the introduction; Procedure; History; Converting from two's complement representation; Sign extension; Most negative number
  2. The Java Language Specification, Java SE 27 Edition, Chapter 15, 15.15.4 Unary Minus Operator -
  3. Bitwise NOT (~), MDN Web Docs, Description
  4. Arithmetic operators, C reference, cppreference.com, Overflows; Unary arithmetic, Notes
  5. Primitive Type i32, The Rust Standard Library, checked_neg; wrapping_neg
  6. The checked and unchecked statements, C# reference, the introduction
  7. P0907R4: Signed Integers are Two's Complement, JF Bastien, 2018, Abstract; 1. Introduction
  8. Fundamental types, C++ reference, cppreference.com, Properties
  9. Arithmetic types, C reference, cppreference.com, Integer types, Properties
  10. Implicit conversions, C++ reference, cppreference.com, Integral conversions
  11. The Java Language Specification, Java SE 27 Edition, Chapter 4, 4.2 Primitive Types and Values
  12. The Go Programming Language Specification, Numeric types
  13. Built-in Types, Python documentation, Bitwise Operations on Integer Types
  14. Math (Java SE 27 and JDK 27), abs(int)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/G7KVME/text.yaml