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)}")
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)}")
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
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the 32-bit bitwise operators and BigInt.asIntN of JavaScript, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin's Byte, Short, Int and Long are two's complement types, as in Java. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | SQL integer types have ranges, but SQL has no operators that show the bits of a value. |
| Bash | Native | Bash arithmetic in $(( )) uses the signed integers of the machine, so $(( ~5 )) is -6. No example file exists. |
| PowerShell | Native | PowerShell uses the .NET signed types, such as [int] and [long]. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no numbers. |
| CSS | Does not apply | CSS has integer values, such as z-index, but no integer types with a width. |
| Regular expressions | Does not apply | A 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.
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))
~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
inthas no width, but bitwise operations act as if it were two's complement with an infinite number of sign bits. x & 0xFFgives the low 8 bits of the two's complement form.to_byteswithsigned=Truewrites 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';
}
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_castshows 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_MINis still undefined behavior.-(INT_MIN + 1)is the largestint.
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));
}
}
-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,intandlongas two's complement integers. - The negation of
Integer.MIN_VALUEis the same value, with no exception.Math.negateExactandMath.absExactthrow anArithmeticExceptioninstead. - A cast from
bytetointcopies the sign bit. The mask& 0xFFkeeps 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;
}
-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_ttoint16_tkeeps the value -6, so the new high bits are copies of the sign bit. -INT_MINis undefined behavior, so the program tests forINT_MINbefore 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");
}
-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,intandlonguse two's complement. - The format
x8prints the bits of a negative value in hexadecimal. The widenedshorthas copies of the sign bit in its high bits. - In the default unchecked context, the negation of
int.MinValueis the same value. In acheckedcontext, it throwsOverflowException.
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));
~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
~xis-(x + 1). x | 0converts 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 ofxas 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)
}
-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
int32is the same value, and the division by -1 gives the same value too. There is no panic.
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());
}
-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
i8toi128andisizeuse two's complement. - Rust writes bitwise NOT as
!. The format{:b}of a signed value prints its two's complement bits. checked_neg,wrapping_negandoverflowing_negsay what to do with the most negative value. A plain-xon that value panics in a debug build.
Variations and related ideas
- 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)andx / -1fail for the most negative value. Java'sMath.absnotes that forInteger.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 useMath.absExact,checked_negor 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) bcopies the sign of abyte, andb & 0xFFgives 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
- Two's complement, Wikipedia, the introduction; Procedure; History; Converting from two's complement representation; Sign extension; Most negative number
- The Java Language Specification, Java SE 27 Edition, Chapter 15, 15.15.4 Unary Minus Operator -
- Bitwise NOT (~), MDN Web Docs, Description
- Arithmetic operators, C reference, cppreference.com, Overflows; Unary arithmetic, Notes
- Primitive Type i32, The Rust Standard Library, checked_neg; wrapping_neg
- The checked and unchecked statements, C# reference, the introduction
- P0907R4: Signed Integers are Two's Complement, JF Bastien, 2018, Abstract; 1. Introduction
- Fundamental types, C++ reference, cppreference.com, Properties
- Arithmetic types, C reference, cppreference.com, Integer types, Properties
- Implicit conversions, C++ reference, cppreference.com, Integral conversions
- The Java Language Specification, Java SE 27 Edition, Chapter 4, 4.2 Primitive Types and Values
- The Go Programming Language Specification, Numeric types
- Built-in Types, Python documentation, Bitwise Operations on Integer Types
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag G7KVME Edit this page History Report an error Markdown