Conceptcore
Integer representation
Also called integer representation, integer type, machine integer, fixed-width integer, signed integer, unsigned integer, two's complement, ones' complement, sign-magnitude, signed number representation, sign extension, zero extension, endianness, byte order, wraparound.
An integer type stores whole numbers in a fixed number of bits. Unsigned types read the bits as a binary number, and almost all machines store signed values in two's complement.
- Applies to
- core-languages
Idea
A machine integer is a fixed number of bits, usually 8, 16, 32 or 64. With N bits there are 2ᴺ patterns, and the type decides which number each pattern means. An unsigned type reads the bits as a binary number, so 8 bits hold 0 to 255. A signed type must also hold negative numbers, and machines have used three ways to do that: sign-magnitude, ones' complement and two's complement. Today almost every processor and every major language uses two's complement, in which the top bit is worth −2ᴺ⁻¹ instead of +2ᴺ⁻¹.
BITS = 8
def sign_magnitude(n):
return (1 << BITS - 1 if n < 0 else 0) | abs(n)
def ones_complement(n):
return n if n >= 0 else ~(-n) & 0xFF # invert every bit
def twos_complement(n):
return n & 0xFF # the same as inverting every bit and adding 1
for n in (5, -5, 0):
print(f"{n:3}: sign-magnitude {sign_magnitude(n):08b} ones' {ones_complement(n):08b} two's {twos_complement(n):08b}")
print("negative zero: sign-magnitude", f"{sign_magnitude(0) | 0x80:08b}", " ones'", f"{0xFF:08b}")
def read_signed(bits):
"""In two's complement the top bit is worth -2^7 instead of +2^7."""
return bits - (1 << BITS) if bits & 1 << BITS - 1 else bits
print("range:", read_signed(0x80), "to", read_signed(0x7F), "| unsigned 0 to", 0xFF)
# The adder does not know about signs: the same bits give both answers.
a, b = 0b11111011, 0b00000111 # 251 and 7, or -5 and 7
s = (a + b) & 0xFF
print(f"{a:08b} + {b:08b} = {s:08b} unsigned: {a} + {b} = {s} (mod 256) signed: {read_signed(a)} + {b} = {read_signed(s)}")
print("127 + 1 =", read_signed((127 + 1) & 0xFF), " -(-128) =", read_signed(-(-128) & 0xFF))
# Sign extension: copy the top bit to widen a value from 8 to 16 bits.
print(f"-5 in 16 bits: {(-5) & 0xFFFF:016b}")
5: sign-magnitude 00000101 ones' 00000101 two's 00000101
-5: sign-magnitude 10000101 ones' 11111010 two's 11111011
0: sign-magnitude 00000000 ones' 00000000 two's 00000000
negative zero: sign-magnitude 10000000 ones' 11111111
range: -128 to 127 | unsigned 0 to 255
11111011 + 00000111 = 00000010 unsigned: 251 + 7 = 2 (mod 256) signed: -5 + 7 = 2
127 + 1 = -128 -(-128) = -128
-5 in 16 bits: 1111111111111011
Sign-magnitude and ones' complement each have two zeros, and they need special rules in the adder. In two's complement, -5 is the bits of 5 inverted plus 1, there is one zero, and the adder for unsigned numbers also gives the right signed answer: 11111011 + 00000111 is 2 whether the first operand means 251 or −5. The price is a range that is not symmetric: 8 bits hold −128 to 127, so −(−128) has no 8-bit answer and wraps back to −128. To widen a signed value, the machine copies the top bit into the new bits, which is sign extension.
How it works
Width and range. An unsigned type of N bits holds 0 to 2ᴺ − 1. A two's complement type of N bits holds −2ᴺ⁻¹ to 2ᴺ⁻¹ − 1, so a 32-bit int holds −2,147,483,648 to 2,147,483,647. Languages name the widths in different ways: int8_t to int64_t in C and C++, i8 to i128 in Rust, sbyte to long and Int128 in C#, and int8 to int64 in Go. Some types follow the machine: size_t, usize, uintptr and nint are as wide as an address, and C's int and long have only minimum widths. Python and JavaScript's BigInt have no fixed width; Python computes bitwise operations "as though carried out in two's complement with an infinite number of sign bits"1.
What the standards require. Java defines byte, short, int and long as "8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers", and char as a 16-bit unsigned type2. C and C++ allowed all three representations for a long time. C++20 made two's complement "the only representation allowed by the standard"3, and C23 did the same4. The C++ proposal, P0907, starts with the sentence "There is One True Representation for signed integers, and that representation is two's complement"5. Neither change made signed overflow defined in C or C++; it is still undefined behavior.
Overflow. An N-bit result that does not fit keeps its low N bits, which is arithmetic modulo 2ᴺ. Languages differ in what the program sees:
- Wrap. Java's "integer operators do not indicate overflow or underflow in any way"2. The Go specification says that signed operations "may legally overflow", that "overflow does not cause a run-time panic", and that a compiler may not assume that overflow does not occur6. C# wraps in its default unchecked context.
- Trap. Rust inserts "dynamic checks that panic on overflow" in debug builds, and a release build may wrap with two's complement results7. Rust also has methods that say what to do:
checked_addreturnsNone,wrapping_addwraps,overflowing_addreturns the wrapped value and a flag, andsaturating_addstops at the limit8. In a C#checkedcontext, overflow throwsSystem.OverflowException9. - Undefined. In C and C++, unsigned arithmetic wraps, but signed overflow is undefined behavior, so the compiler can assume that it never happens. C23 adds
ckd_add,ckd_subandckd_mul, which return true when the mathematical result does not fit10. - Grow. Python integers and JavaScript
BigIntvalues grow as needed and never overflow.
Conversions. A narrowing conversion keeps the low bits, so 200 in a signed 8-bit type is −56. A widening conversion of a signed value copies the sign bit, and a widening conversion of an unsigned value adds zero bits, so the byte 0xFB becomes −5 or 251 depending on its type. In C and C++, an operation on a signed and an unsigned operand of the same rank first converts the signed operand to unsigned, so -1 < 1u is false. C++20 adds std::cmp_less and std::in_range, which compare the mathematical values.
Shifts. A left shift by k multiplies by 2ᵏ and drops the bits that go past the top. A right shift has two forms: an arithmetic shift copies the sign bit, so -16 >> 2 is −4, and a logical shift fills with zeros. Java, JavaScript and C# write the logical shift as >>>; C, C++, Go and Rust choose by the type, so they shift an unsigned value logically.
Byte order. A multi-byte integer is stored in memory as a sequence of bytes. A little-endian machine, such as x86 or the usual configuration of ARM, puts the lowest byte first; a big-endian layout, which network protocols use, puts the highest byte first. Code that reads or writes files and network data must name the order. JavaScript typed arrays use the order of the platform, and a DataView lets the program choose, with big-endian as the default11.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | TypeScript has the typed arrays, DataView, BigInt and 32-bit bitwise operators of JavaScript, and its type number is a 64-bit float, but no example file exists. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has Byte, Short, Int and Long in two's complement and the unsigned types UByte, UShort, UInt and ULong, but no example file exists because kotlinc is not installed. |
| SQL | Native | SQL has the exact numeric types SMALLINT, INTEGER and BIGINT, and a value out of range is an error, but the widths of the types depend on the database. |
| Bash | Native | Bash arithmetic uses fixed-width signed integers, usually 64 bits, with no check for overflow, but no example file exists. |
| PowerShell | Native | PowerShell uses the .NET integer types, such as [int], [long], [byte] and [uint64], but 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 does not state their width or representation. |
| Regular expressions | Does not apply | A pattern matches digits as text but has no integer types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | int of any size; int.to_bytes, int.from_bytes; struct, array and ctypes for fixed widths |
| JavaScript | native | 32-bit bitwise operators; Int8Array to BigInt64Array; DataView; BigInt.asIntN |
| TypeScript | native | as JavaScript |
| Java | native | byte, short, int, long in two's complement; char; unsigned methods of Integer and Long |
| Kotlin | native | Byte to Long; UByte to ULong |
| C# | native | sbyte to long, byte to ulong, Int128, nint; checked and unchecked |
| Go | native | int8 to int64, uint8 to uint64, int, uintptr; defined wraparound |
| Rust | native | i8 to i128, u8 to u128, isize, usize; checked_*, wrapping_*, saturating_* |
| C | native | signed char to long long; <stdint.h>; <stdckdint.h> |
| C++ | native | as C; std::numeric_limits, std::bit_cast, std::cmp_less, std::byteswap |
| Bash | native | fixed-width signed arithmetic in $(( )), usually 64 bits, with no overflow check |
| PowerShell | native | .NET integer types such as [int], [long], [byte] |
| SQL | native | SMALLINT, INTEGER, BIGINT; overflow is an error |
| Regex | n/a | no numbers |
| HTML | n/a | no numbers |
| CSS | n/a | integer values with no stated width |
All the general-purpose languages in the table have integer types, so the verdict is native. They differ in three choices: which widths they name, whether they have unsigned types, and what happens on overflow. Java has no unsigned int or long, but its Integer and Long classes have unsigned methods. Python has one integer type with no width, and it gives fixed-width values only through int.to_bytes and modules such as struct, array and ctypes.
The example files show these choices. Python packs a value into bytes in each byte order. JavaScript reads one byte as unsigned and signed. Java shows the wrap of int and the error of Math.addExact. C# shows checked and unchecked. Go shows wraparound and the most negative value divided by −1. Rust shows the four kinds of addition. C shows ckd_add and the signed and unsigned comparison, and C++ shows std::bit_cast and std::cmp_less. The C and C++ files print bytes in the order of the machine, so their output is for a little-endian machine.
import struct
n = -1000
# int.to_bytes needs a width, a byte order and a choice of signed or unsigned.
print(n.to_bytes(2, "big", signed=True).hex(" "), n.to_bytes(2, "little", signed=True).hex(" "))
print(int.from_bytes(b"\xfc\x18", "big", signed=True), int.from_bytes(b"\xfc\x18", "big"))
try:
(300).to_bytes(1, "big")
except OverflowError as e:
print("OverflowError:", e)
# struct packs C types: < is little-endian, > is big-endian; h is a 16-bit short, I a 32-bit unsigned int.
print(struct.pack("<h", -2).hex(" "), struct.pack(">I", 1).hex(" "))
print(struct.unpack("<H", struct.pack("<h", -2))[0])
# Python ints have no width, so they never overflow.
print(2**64 + 1, (-7) // 2, -7 % 2)
fc 18 18 fc
-1000 64536
OverflowError: int too big to convert
fe ff 00 00 00 01
65534
18446744073709551617 -4 1
- Verdict: native. A Python
inthas no fixed width, so it never overflows, and2**64 + 1is exact. To get fixed-width bytes,int.to_bytestakes a length, a byte order and asignedflag, and it raisesOverflowErrorwhen the value does not fit. Thestructmodule packs C types, with<for little-endian and>for big-endian. Integer division and%round toward negative infinity, so-7 // 2is −4.
#include <bit>
#include <cstdint>
#include <iostream>
#include <limits>
#include <utility>
int main() {
// The same 8 bits read as unsigned and as two's complement.
std::uint8_t u = 251;
std::cout << +u << ' ' << +std::bit_cast<std::int8_t>(u) << '\n';
using L = std::numeric_limits<std::int16_t>;
std::cout << L::min() << ' ' << L::max() << ' ' << L::digits << " value bits\n";
// The built-in comparison converts -1 to unsigned first; std::cmp_less compares the values.
int neg = -1;
unsigned one = 1;
std::cout << std::boolalpha << (static_cast<unsigned>(neg) < one) << ' ' << std::cmp_less(neg, one) << '\n';
std::cout << std::in_range<std::uint8_t>(300) << ' ' << std::in_range<std::int8_t>(-5) << '\n';
// The byte order of the machine, and a byte swap.
std::cout << (std::endian::native == std::endian::little ? "little" : "big") << "-endian\n";
std::cout << std::hex << std::byteswap(std::uint32_t{0x11223344}) << '\n';
}
251 -5
-32768 32767 15 value bits
false true
false true
little-endian
44332211
- Verdict: native. C++ has the integer types of C and the same undefined signed overflow.
std::bit_castreads the bits of auint8_tas anint8_t, andstd::numeric_limitsgives the range and the number of value bits.std::cmp_lessandstd::in_rangecompare mathematical values, so they give the right answer where the built-in comparison converts −1 to unsigned.std::endiannames the byte order of the machine, andstd::byteswapreverses the bytes.
public class Main {
public static void main(String[] args) {
byte b = (byte) 200; // the cast keeps the low 8 bits
System.out.println(b + " " + Byte.toUnsignedInt(b));
int max = Integer.MAX_VALUE;
System.out.println((max + 1) + " " + Math.abs(Integer.MIN_VALUE)); // int arithmetic wraps
try {
Math.addExact(max, 1);
} catch (ArithmeticException e) {
System.out.println("addExact: " + e.getMessage());
}
// >> copies the sign bit; >>> shifts in zeros.
System.out.println((-16 >> 2) + " " + (-16 >>> 28));
// Java has no unsigned int type, but Integer has unsigned methods.
System.out.println(Integer.toUnsignedString(-1) + " " + Integer.divideUnsigned(-1, 2) + " " + Integer.compareUnsigned(-1, 1));
System.out.println((long) b + " " + (b & 0xFFL)); // widening keeps the sign; a mask does not
}
}
-56 200
-2147483648 -2147483648
addExact: integer overflow
-4 15
4294967295 2147483647 1
-56 200
- Verdict: native. Java's integer types are signed two's complement, and
intarithmetic wraps with no error, soInteger.MAX_VALUE + 1is the most negativeintandMath.abs(Integer.MIN_VALUE)is negative.Math.addExactthrowsArithmeticExceptioninstead. The cast(byte) 200keeps the low 8 bits, which read as −56, andByte.toUnsignedIntor& 0xFFgives 200 back. Java has no unsignedint, butIntegerhas unsigned methods, and>>>is the logical right shift.
#include <inttypes.h>
#include <limits.h>
#include <stdckdint.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
int main(void) {
/* Unsigned arithmetic is defined to wrap modulo 2^N. */
uint8_t u = 0;
u = (uint8_t)(u - 1);
printf("%u %u\n", (unsigned)u, UINT_MAX);
/* Signed overflow is undefined behavior, so check before the operation, or use ckd_add. */
int a = INT_MAX, b = 1, r;
if (b > 0 && a > INT_MAX - b)
puts("a + b would overflow");
if (ckd_add(&r, a, b))
printf("ckd_add: overflow, wrapped result %d\n", r);
printf("%d %d\n", INT_MIN, INT_MAX);
/* Widening a signed value copies the sign bit; widening an unsigned value adds zeros. */
int8_t s = -5;
printf("%" PRId32 " %" PRIu32 "\n", (int32_t)s, (uint32_t)(uint8_t)s);
/* The comparison converts -1 to unsigned, so it is false. */
int neg = -1;
unsigned one = 1;
printf("-1 < 1u: %d\n", neg < one);
/* The bytes of an int in memory follow the byte order of the machine. */
int32_t v = -1000;
unsigned char bytes[4];
memcpy(bytes, &v, sizeof v);
printf("%02x %02x %02x %02x\n", bytes[0], bytes[1], bytes[2], bytes[3]);
return 0;
}
255 4294967295
a + b would overflow
ckd_add: overflow, wrapped result -2147483648
-2147483648 2147483647
-5 251
-1 < 1u: 0
18 fc ff ff
- Verdict: native. C has signed and unsigned types and the exact widths of
<stdint.h>. Unsigned arithmetic wraps modulo 2ᴺ, but signed overflow is undefined behavior, so the program tests before the addition or usesckd_addfrom<stdckdint.h>, which returns true and stores the wrapped result. The comparison-1 < 1uconverts −1 to unsigned and is false. The last line shows the bytes of anint32_tin memory, here on a little-endian machine.
using System.Buffers.Binary;
int max = int.MaxValue;
Console.WriteLine(unchecked(max + 1)); // wraps in an unchecked context
try
{
Console.WriteLine(checked(max + 1));
}
catch (OverflowException e)
{
Console.WriteLine($"checked: {e.GetType().Name}");
}
int v = 200, w = -5;
Console.WriteLine($"{(sbyte)v} {(byte)w} {sbyte.MinValue} {byte.MaxValue}"); // casts of variables wrap by default
Console.WriteLine($"{uint.MaxValue} {(uint)int.MaxValue + 1u} {Int128.MaxValue}");
// Write an int in each byte order.
var bytes = new byte[4];
BinaryPrimitives.WriteInt32BigEndian(bytes, -1000);
Console.WriteLine(Convert.ToHexString(bytes));
BinaryPrimitives.WriteInt32LittleEndian(bytes, -1000);
Console.WriteLine(Convert.ToHexString(bytes));
Console.WriteLine($"{-16 >> 2} {-16 >>> 28}");
-2147483648
checked: OverflowException
-56 251 -128 255
4294967295 2147483648 170141183460469231731687303715884105727
FFFFFC18
18FCFFFF
-4 15
- Verdict: native. C# has signed and unsigned types from 8 to 128 bits. Arithmetic is unchecked by default, so
int.MaxValue + 1wraps, and in acheckedexpression the same addition throwsOverflowException. A cast of a variable keeps the low bits.BinaryPrimitiveswrites an integer in a stated byte order, and>>>is the logical right shift.
// Two views of the same byte: unsigned and two's complement.
const buf = new ArrayBuffer(1);
const u8 = new Uint8Array(buf);
const i8 = new Int8Array(buf);
u8[0] = 251;
console.log(u8[0], i8[0]);
i8[0] = 200; // stored modulo 256, then read as signed
console.log(i8[0], u8[0]);
// Bitwise operators convert to a 32-bit signed integer.
console.log(2 ** 31 | 0, (2 ** 32 + 5) | 0, -1 >>> 0);
console.log(Math.imul(0x7fffffff, 2)); // 32-bit multiply that wraps
// BigInt wraps only when asked.
console.log(BigInt.asIntN(8, 200n), BigInt.asUintN(64, -1n));
// A DataView reads integers of a given size and byte order.
const v = new DataView(new ArrayBuffer(2));
v.setInt16(0, -1000); // big-endian by default
console.log(v.getUint8(0).toString(16), v.getUint8(1).toString(16), v.getInt16(0, true));
251 -5
-56 200
-2147483648 5 4294967295
-2
-56n 18446744073709551615n
fc 18 6396
- Verdict: native. A JavaScript number is a 64-bit float, but the bitwise operators convert it to a 32-bit two's complement integer, so
2 ** 31 | 0is negative, and>>> 0reads the bits as unsigned. AUint8Arrayand anInt8Arrayon the same buffer read one byte as 251 and as −5.Math.imulmultiplies with 32-bit wraparound,BigInt.asIntNwraps aBigIntto a given width, and aDataViewreads and writes in either byte order.
package main
import (
"encoding/binary"
"fmt"
"math"
)
func main() {
x := 200
fmt.Println(int8(x), uint8(x+100)) // a conversion keeps the low bits
var i int32 = math.MaxInt32
i++ // Go defines signed overflow: it wraps
fmt.Println(i)
m := int64(math.MinInt64)
fmt.Println(m/-1, -m == m) // the spec says x / -1 equals x for the most negative value
var u uint8 = 0
u--
fmt.Println(u, ^uint32(0))
var k int16 = -1000
b := binary.BigEndian.AppendUint16(nil, uint16(k))
fmt.Printf("% x % x\n", b, binary.LittleEndian.AppendUint16(nil, uint16(k)))
fmt.Println(int16(binary.BigEndian.Uint16(b)))
fmt.Println(-16>>2, uint32(0xF0000000)>>28)
}
-56 44
-2147483648
-9223372036854775808 true
255 4294967295
fc 18 18 fc
-1000
-4 15
- Verdict: native. Go has
int8toint64anduint8touint64, and its specification defines overflow: signed and unsigned arithmetic wrap, with no panic. The most negativeint64divided by −1 is itself, as the specification says. A conversion such asint8(x)keeps the low bits.encoding/binarywrites and reads integers in big-endian and little-endian order.
fn main() {
let x: i32 = i32::MAX;
// + panics on overflow in a debug build, so Rust has methods that say what to do.
println!("{:?} {} {:?} {}", x.checked_add(1), x.wrapping_add(1), x.overflowing_add(1), x.saturating_add(1));
println!("{:?} {}", i8::MIN.checked_abs(), i8::MIN.unsigned_abs());
// `as` keeps the low bits, and widening a signed value copies the sign bit.
println!("{} {} {} {}", 200i32 as i8, -5i8 as u8, -5i8 as i32, -5i8 as u8 as i32);
println!("{} {:?}", u8::try_from(300i32).is_err(), i8::try_from(-5i32));
// Byte order is explicit.
println!("{:02x?} {:02x?}", (-1000i16).to_be_bytes(), (-1000i16).to_le_bytes());
println!("{}", i16::from_be_bytes([0xfc, 0x18]));
println!("{} {}", -16i32 >> 2, (-16i32 as u32) >> 28);
}
None -2147483648 (-2147483648, true) 2147483647
None 128
-56 251 -5 251
true Ok(-5)
[fc, 18] [18, fc]
-1000
-4 15
- Verdict: native. Rust has
i8toi128andu8tou128. In a debug build,+panics on overflow, so the program uses methods that state the rule:checked_addreturnsNone,wrapping_addwraps,overflowing_addreturns a flag, andsaturating_addstops at the limit.askeeps the low bits or extends the sign, andtry_fromreturns an error when the value does not fit.to_be_bytesandto_le_bytesgive each byte order.
Variations and related ideas
- Sign-magnitude and ones' complement. Floating-point numbers store their significand in sign-magnitude, and the Internet checksum adds 16-bit words in ones' complement. See floating-point arithmetic.
- Offset binary. A biased form stores x + K, so the bits sort in the same order as the values. The exponent of an IEEE 754 float is stored this way.
- Arbitrary precision. Python
int, JavaScriptBigInt, JavaBigInteger, C#BigIntegerand Gomath/bigstore integers of any size as arrays of machine words. - Saturating arithmetic. A result that is too large becomes the largest value. Signal processing and image code use it, and SIMD instruction sets have saturating instructions.
- Bit-precise types. C23 adds
_BitInt(N)for any width up to a limit of the implementation, and hardware description languages have integers of any width. - Checked conversions. Rust
try_from, C++std::in_rangeand Go code that compares againstmath.MaxInt8test that a value fits before a narrowing conversion. See type conversion and parse an integer.
Pitfalls
- Signed overflow in C and C++. The compiler may assume that signed overflow does not occur, so it can remove a check such as
if (x + 1 < x). Check before the operation, useckd_add, or use unsigned arithmetic. See integer overflow. - The most negative value.
abs, negation and division by −1 of the most negative value have no answer in the same type. Java'sMath.abs(Integer.MIN_VALUE)returns the negative value itself, and in C the operation is undefined behavior. - Signed and unsigned mixes. In C and C++,
-1 < 1uis false andsizeofvalues are unsigned, sofor (unsigned i = n - 1; i >= 0; i--)never ends. Compiler warnings such as-Wsign-compareand-Wtype-limitsfind many of these. - Bytes that become negative. Java's
byteis signed, so a byte of 200 read from a file is −56, and(int) bkeeps −56. Mask with& 0xFFto get 0 to 255. - Silent narrowing. A cast to a smaller type drops the high bits with no error in C, C++, Java, C#, Go and Rust's
as. Check the range first, or use a conversion that fails. - Division of negative numbers. C, C++, Java, C#, Go and Rust round the integer quotient toward zero, so
-7 / 2is −3 and-7 % 2is −1, and the JavaScript%operator has the same sign rule. Python rounds toward negative infinity, so-7 // 2is −4 and-7 % 2is 1. - Byte order in data. Bytes copied from memory to a file or a socket carry the order of the machine. Convert with explicit functions, such as
int.to_bytes,DataView,binary.BigEndianorto_be_bytes.
Cost
An add, subtract, compare or shift of a machine integer is one instruction, which usually takes one cycle. Multiplication takes a few cycles, and division takes more. A checked operation adds a branch on the overflow flag, which the processor nearly always predicts correctly, but it can stop the compiler from vectorizing a loop. Wider types use more memory and cache: an array of int64 is twice the size of an array of int32. Arbitrary-precision integers cost O(n) for addition of n-word values and more for multiplication.
History
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 it12. Other early machines chose differently: the IBM 7090 used sign-magnitude, and the PDP-1, the CDC 6600 and the UNIVAC 1100 series used ones' complement13. The IBM System/360 of 1964 made two's complement the most widely used representation12, and the PDP-8, the PDP-11, the VAX and the Intel 8080 used it too13.
The C standard allowed all three representations5. Java fixed two's complement and the widths of its types in its specification2. JF Bastien's proposal P0907 of 2018 made two's complement the only representation in C++205, and C23 followed4.
References
- Built-in Types, Python documentation, Bitwise Operations on Integer Types; int.to_bytes()
- The Java Language Specification, Java SE 25 Edition, Chapter 4, 4.2 Primitive Types and Values; 4.2.2 Integer Operations
- Fundamental types, C++ reference, cppreference.com, Properties
- Arithmetic types, C reference, cppreference.com, Integer types, Properties
- P0907R4: Signed Integers are Two's Complement, JF Bastien, 2018, Abstract
- The Go Programming Language Specification, Integer overflow
- Behavior not considered unsafe, The Rust Reference, Integer overflow
- Primitive Type i32, Rust standard library documentation, checked_add, wrapping_add, overflowing_add, saturating_add
- The checked and unchecked statements, C# language reference, Description
- ckd_add, C reference, cppreference.com, Return value
- JavaScript typed arrays, MDN Web Docs, Typed array views; Endianness
- Two's complement, Wikipedia, History
- Signed number representations, Wikipedia, History
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 ZG7TDD Edit this page History Report an error Markdown