Programming Search⌘K

Conceptcore

Signed and unsigned integers

Also called signedness, signed integer, unsigned integer, unsigned type, signed and unsigned comparison, sign-compare, usual arithmetic conversions, unsigned wraparound.

A signed integer type holds negative and positive values, and an unsigned type of the same width holds only zero and positive values. Mixing the two in one expression can change a value.

Applies to
core-languages

Idea

An integer type has a fixed number of bits, and its signedness decides what the bit patterns mean. "A numeric variable is signed if it can represent both positive and negative numbers, and unsigned if it can only represent non-negative numbers (zero or positive numbers)."1 The two kinds of the same width have the same number of values, but the ranges are not the same. An 8-bit unsigned type holds 0 to 255, and an 8-bit signed type holds -128 to 127.

The same bits can mean two numbers. The 8 bits 11111111 are 255 as an unsigned value and -1 as a signed value in two's complement:

for bits in (0b00000001, 0b01111111, 0b10000000, 0b11111111):
    signed = bits - 256 if bits >= 128 else bits
    print(f"{bits:08b}  unsigned {bits:3}  signed {signed:4}")
Output
00000001  unsigned   1  signed    1
01111111  unsigned 127  signed  127
10000000  unsigned 128  signed -128
11111111  unsigned 255  signed   -1

The patterns from 00000000 to 01111111 mean the same number in both types. The patterns with the top bit set are large numbers to an unsigned type and negative numbers to a signed type. Most problems with signedness come from this difference: a conversion keeps the bits and changes the number.

How it works

Ranges. A signed type of n bits stores the numbers from -(2ⁿ⁻¹) to 2ⁿ⁻¹ - 1, and an unsigned type stores 0 to 2ⁿ - 1. The Rust book gives this rule, so an i8 holds -128 to 127 and a u8 holds 0 to 2552. The C# reference lists the ranges of its types: int is "-2,147,483,648 to 2,147,483,647" and uint is "0 to 4,294,967,295"3. A signed type gives up half of the large positive values to hold the negative values.

Conversions keep the bits. A conversion between a signed and an unsigned type of the same width keeps the bit pattern in most languages. In Rust, a cast "between two integers of the same size (e.g. i32 -> u32) is a no-op"4. In C, a value that does not fit an unsigned target is changed by a multiple of 2ⁿ until it fits: "In other words, unsigned integers implement modulo arithmetic."5 For a signed target, "the behavior is implementation-defined (which may include raising a signal)."5 Go defines both directions. A signed value "is sign extended to implicit infinite precision; otherwise it is zero extended. It is then truncated to fit in the result type's size."6

Mixed expressions. An operation on a signed and an unsigned value needs one type for both. Languages choose four different rules:

  • Convert to unsigned. In C and C++, after the integer promotions, "If the unsigned type has conversion rank greater than or equal to the rank of the signed type, then the operand with the signed type is implicitly converted to the unsigned type."5 So in -1 < 1u, the -1 becomes the largest unsigned int, and the result is false.
  • Convert to a wider signed type. In C#, "If the operands are different integral or floating-point types, their values are converted to the closest containing type, if such a type exists."7 An int and a uint both become long, so -1 < 1u is true.
  • Refuse to compile. Go says: "Explicit conversions are required when different numeric types are mixed in an expression or assignment."6 Rust also needs a conversion before it compares an i32 with a u32.
  • Have one integer type. Python integers "have unlimited precision"8, so there is no unsigned type to mix.

Safe comparisons. C++20 added std::cmp_less and its relatives. "Unlike builtin comparison operators, negative signed integers always compare less than (and not equal to) unsigned integers: the comparison is safe against non-value-preserving integer conversion."9 In Go, C# and Rust, the program converts both values to a wider signed type, or tests the sign first.

Languages without unsigned types. Java's integral types byte, short, int and long are "8-bit, 16-bit, 32-bit and 64-bit signed two's-complement integers, respectively"10. The one unsigned integral type is char, which holds 16-bit UTF-16 code units10. For unsigned work, the Integer class has methods such as compareUnsigned, which "Compares two int values numerically treating the values as unsigned."11 JavaScript numbers are not integers of a fixed width, but the operator >>> gives an unsigned 32-bit result. MDN shows -9 >>> 2 as 107374182112. Python has no fixed-width types. Its int.to_bytes and int.from_bytes take a signed argument, which selects two's complement for the bytes8.

In languages

LanguageVerdictNote
PythonAbsent
C++Native
JavaStandard library
CNative
C#Native
JavaScriptIdiom
TypeScriptIdiomTypeScript has the number type, the >>> operator and the typed arrays of JavaScript, so it has unsigned views but no unsigned integer type. No example file exists.
GoNative
RustNative
KotlinNativeKotlin has the unsigned types UByte, UShort, UInt and ULong next to its signed types. No example file exists because kotlinc is not installed.
SQLAbsentThe SQL integer types SMALLINT, INTEGER and BIGINT are signed. A CHECK constraint can refuse negative values.
BashAbsentBash arithmetic uses one signed integer type. A script prints a value as unsigned with printf and the %u format.
PowerShellNativePowerShell uses the .NET types, such as [byte], [uint16], [uint32] and [uint64]. 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 or a sign rule.
Regular expressionsDoes not applyA pattern matches digits as text but has no integer types.
Language Verdict Unsigned types and mixed rules
Python absent one int with no width; signed= in to_bytes and from_bytes
JavaScript idiom no unsigned Number; >>> 0 and Uint8Array to Uint32Array, BigUint64Array
TypeScript idiom as JavaScript
Java stdlib only char is unsigned; Integer and Long have unsigned methods
Kotlin native UByte, UShort, UInt, ULong
C# native byte, ushort, uint, ulong, nuint; mixed operands become a wider type
Go native uint8 to uint64, uint, uintptr; mixed operands do not compile
Rust native u8 to u128, usize; mixed operands do not compile
C native unsigned types; mixed operands often become unsigned
C++ native as C; std::cmp_less and its relatives
Bash absent signed arithmetic only
PowerShell native the .NET types, such as [uint32] and [byte]
SQL absent SMALLINT, INTEGER and BIGINT are signed
Regex n/a no numbers
HTML n/a no numbers
CSS n/a no integer types with a width

The verdict tells whether a language has unsigned integer types. Native languages have them as types of the language. Java has only char, and its standard library gives unsigned operations on signed types. JavaScript gets an unsigned view with an operator or a typed array. Python and Bash have no unsigned integer type.

The example files show the same ideas in each language. Python reads two bytes as unsigned and as signed. JavaScript uses >>> and typed arrays. Java uses the unsigned methods of Integer. C and C++ show a mixed comparison that gives the wrong answer, and C++ fixes it with std::cmp_greater. C# shows that int and uint become long. Go and Rust convert by hand, because a mixed expression does not compile.

PythonGitHub
raw = bytes([0xFF, 0xFE])
print("unsigned:", int.from_bytes(raw, "big"))
print("signed:", int.from_bytes(raw, "big", signed=True))
print("-1 as 32-bit unsigned:", -1 & 0xFFFF_FFFF)
print("-2 to 2 bytes, signed:", (-2).to_bytes(2, "big", signed=True).hex())
try:
    (-2).to_bytes(2, "big")
except OverflowError:
    print("-2 to 2 bytes, unsigned: OverflowError")
Output
unsigned: 65534
signed: -2
-1 as 32-bit unsigned: 4294967295
-2 to 2 bytes, signed: fffe
-2 to 2 bytes, unsigned: OverflowError
  • Verdict: absent. Python has one integer type, and it has no width and no unsigned form.
  • Signedness matters only at the edge of the program, where bytes come in or go out. from_bytes and to_bytes take signed=True for two's complement.
  • x & 0xFFFF_FFFF gives the unsigned 32-bit value of a negative number.
  • to_bytes without signed=True refuses a negative number with OverflowError.
#include <iostream>
#include <utility>
#include <vector>

const char* yes_no(bool b) { return b ? "yes" : "no"; }

int main() {
    int minus_one = -1;
    unsigned int zero = 0;
    std::cout << "-1 > 0u: " << yes_no(minus_one > zero) << '\n';
    std::cout << "std::cmp_greater(-1, 0u): " << yes_no(std::cmp_greater(minus_one, zero)) << '\n';

    std::vector<int> empty;
    std::cout << "empty.size() - 1 > 0: " << yes_no(empty.size() - 1 > 0) << '\n';
    std::cout << "std::cmp_less(-1, empty.size()): " << yes_no(std::cmp_less(-1, empty.size())) << '\n';
}
Output
-1 > 0u: yes
std::cmp_greater(-1, 0u): no
empty.size() - 1 > 0: yes
std::cmp_less(-1, empty.size()): yes
  • Verdict: native. C++ has the unsigned types of C, and size() of the standard containers returns an unsigned type.
  • The built-in operators convert -1 to unsigned, so -1 > 0u is true.
  • std::cmp_greater, std::cmp_less and the other functions of <utility> compare the mathematical values. They need C++20.
  • empty.size() - 1 wraps to the largest size_t. Compare with std::cmp_less, or convert the size to a signed type first.
JavaGitHub
public class Main {
  static String yesNo(boolean b) {
    return b ? "yes" : "no";
  }

  public static void main(String[] args) {
    byte b = (byte) 200;
    System.out.println("(byte) 200: " + b);
    System.out.println("Byte.toUnsignedInt(b): " + Byte.toUnsignedInt(b));

    int x = -1;
    System.out.println("Integer.toUnsignedString(-1): " + Integer.toUnsignedString(x));
    System.out.println("-1 < 1 as signed: " + yesNo(x < 1));
    System.out.println("-1 < 1 as unsigned: " + yesNo(Integer.compareUnsigned(x, 1) < 0));
    System.out.println("Integer.divideUnsigned(-2, 2): " + Integer.divideUnsigned(-2, 2));
  }
}
Output
(byte) 200: -56
Byte.toUnsignedInt(b): 200
Integer.toUnsignedString(-1): 4294967295
-1 < 1 as signed: yes
-1 < 1 as unsigned: no
Integer.divideUnsigned(-2, 2): 2147483647
  • Verdict: stdlib. Java has no unsigned int or long, and byte is signed. Only char is unsigned.
  • The classes Byte, Integer and Long read a signed value as unsigned. Integer.compareUnsigned and Integer.divideUnsigned give the unsigned result for the same bits.
  • Addition, subtraction and multiplication need no unsigned method, because they give the same bits for both readings.
#include <limits.h>
#include <stdint.h>
#include <stdio.h>

int main(void) {
    int minus_one = -1;
    unsigned int one = 1;
    printf("-1 < 1u: %s\n", minus_one < one ? "yes" : "no");
    printf("(unsigned int) -1 == UINT_MAX: %s\n", (unsigned int) minus_one == UINT_MAX ? "yes" : "no");

    unsigned int three = 3;
    unsigned int five = 5;
    printf("3u - 5u > 0: %s\n", three - five > 0 ? "yes" : "no");

    int16_t small = -1;
    uint8_t byte = 200;
    printf("int16_t -1 < uint8_t 200: %s\n", small < byte ? "yes" : "no");
    return 0;
}
Output
-1 < 1u: no
(unsigned int) -1 == UINT_MAX: yes
3u - 5u > 0: yes
int16_t -1 < uint8_t 200: yes
  • Verdict: native. C has an unsigned form of each integer type, and <stdint.h> has uint8_t to uint64_t.
  • In -1 < 1u, both operands have the rank of int, so the signed operand becomes unsigned int, and -1 becomes the largest value.
  • An unsigned subtraction that goes below zero wraps to a large value, so 3u - 5u is more than 0.
  • Types smaller than int first become int, so the comparison of int16_t and uint8_t is a signed comparison and gives the right answer.
using System;

static string YesNo(bool b) => b ? "yes" : "no";

int minusOne = -1;
uint one = 1;
Console.WriteLine($"-1 < 1u: {YesNo(minusOne < one)}");
Console.WriteLine($"type of -1 + 1u: {(minusOne + one).GetType().Name}");
Console.WriteLine($"unchecked((uint)-1): {unchecked((uint)minusOne)}");

byte b = 200;
Console.WriteLine($"unchecked((sbyte)200): {unchecked((sbyte)b)}");
try
{
    Console.WriteLine(checked((uint)minusOne));
}
catch (OverflowException)
{
    Console.WriteLine("checked((uint)-1): OverflowException");
}
Output
-1 < 1u: yes
type of -1 + 1u: Int64
unchecked((uint)-1): 4294967295
unchecked((sbyte)200): -56
checked((uint)-1): OverflowException
  • Verdict: native. C# has byte, ushort, uint, ulong and nuint next to the signed types. byte is unsigned and sbyte is signed.
  • An int and a uint both become long, which holds all of their values, so -1 < 1u is true.
  • A cast in an unchecked context keeps the bits. In a checked context, a value that does not fit throws OverflowException.
JavaScriptGitHub
console.log("-1 >>> 0:", -1 >>> 0);
console.log("-9 >>> 2:", -9 >>> 2);

const bytes = new Uint8Array([200, 255, 256, -1]);
console.log("Uint8Array:", bytes.join(" "));
console.log("Int8Array view:", new Int8Array(bytes.buffer).join(" "));
Output
-1 >>> 0: 4294967295
-9 >>> 2: 1073741821
Uint8Array: 200 255 0 255
Int8Array view: -56 -1 0 -1
  • Verdict: idiom. A JavaScript number is not an integer of a fixed width, so there is no unsigned number type.
  • x >>> 0 gives the unsigned 32-bit value of x. The operator >>> fills the left bits with zeros.
  • A Uint8Array stores each value modulo 256, so 256 becomes 0 and -1 becomes 255. An Int8Array on the same buffer reads the same bytes as signed values.
package main

import "fmt"

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

func main() {
	var a int32 = -1
	var b uint32 = 1
	// a < b does not compile: the types differ.
	fmt.Println("uint32(a):", uint32(a))
	fmt.Println("uint32(a) < b:", yesNo(uint32(a) < b))
	fmt.Println("int64(a) < int64(b):", yesNo(int64(a) < int64(b)))

	var x, y uint32 = 3, 5
	fmt.Println("x - y:", x-y)
}
Output
uint32(a): 4294967295
uint32(a) < b: no
int64(a) < int64(b): yes
x - y: 4294967294
  • Verdict: native. Go has uint8 to uint64, uint and uintptr, and byte is another name for uint8.
  • Go does not convert between numeric types by itself. The program must choose the conversion, and the choice decides the answer.
  • int64 holds all values of int32 and uint32, so a comparison after the conversion to int64 is correct.
  • Unsigned arithmetic wraps, so 3 - 5 in uint32 is 4294967294.
RustGitHub
fn main() {
    let a: i32 = -1;
    let b: u32 = 1;
    // a < b does not compile: the types differ.
    println!("a as u32: {}", a as u32);
    println!("a.cast_unsigned(): {}", a.cast_unsigned());
    println!("u32::try_from(a): {}", if u32::try_from(a).is_ok() { "ok" } else { "error" });
    println!("i64::from(a) < i64::from(b): {}", if i64::from(a) < i64::from(b) { "yes" } else { "no" });

    println!("3u32.checked_sub(5): {:?}", 3u32.checked_sub(5));
    println!("i32::MIN.unsigned_abs(): {}", i32::MIN.unsigned_abs());
}
Output
a as u32: 4294967295
a.cast_unsigned(): 4294967295
u32::try_from(a): error
i64::from(a) < i64::from(b): yes
3u32.checked_sub(5): None
i32::MIN.unsigned_abs(): 2147483648
  • Verdict: native. Rust has u8 to u128 and usize next to the signed types.
  • Rust does not compare or add an i32 and a u32. as and cast_unsigned keep the bits, try_from fails when the value does not fit, and i64::from widens with no loss.
  • checked_sub returns None when an unsigned result would go below zero.
  • unsigned_abs returns a u32, so the absolute value of i32::MIN fits.
  • Sign representations. A signed type needs a way to store the sign. Almost all machines use two's complement, and older machines also used ones' complement and sign-magnitude. See Two's complement and Ones' complement and sign-magnitude.
  • Overflow. An unsigned result that does not fit wraps modulo 2ⁿ in C, C++, Go and C#. Signed overflow has different rules in each language. See Integer overflow behaviour and Integer overflow or wraparound.
  • Character types. In C, plain char is "Equivalent to either signed char or unsigned char (which one is implementation-defined and may be controlled by a compiler commandline switch)"13. Java's char is unsigned10.
  • Size types. size_t in C and C++, usize in Rust and nuint in C# are unsigned types with the width of an address. The C# reference says that nint and nuint "are native-sized integers"3.
  • Same bits, other view. Rust's cast_unsigned "Returns the bit pattern of self reinterpreted as an unsigned integer of the same size."14 Its unsigned_abs "Computes the absolute value of self without any wrapping or panicking."14 It returns an unsigned value, so the absolute value of i32::MIN fits.

Pitfalls

  • A mixed comparison in C and C++. -1 < 1u is false, because -1 becomes the largest unsigned int. "Compilers often issue a warning when comparisons are made between signed and unsigned numbers or when one is cast to the other."1 Turn on -Wsign-compare, and use std::cmp_less in C++.
  • An unsigned count that goes below zero. In C++, v.size() - 1 on an empty vector is the largest size_t, not -1. A loop such as for (auto i = vec.size()-1; i >= 0; i -= 2) is marked as a bug in the C++ Core Guidelines15, because an unsigned i is always 0 or more.
  • An unsigned type does not stop negative values. The C++ Core Guidelines say: "Using unsigned doesn’t actually eliminate the possibility of negative values."15 Their example assigns -2 to an unsigned int and gets 4294967294. The Google C++ Style Guide says: "In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this."16
  • Bytes in Java are signed. A byte with the bits 11001000 reads as -56, not 200. Mask with & 0xFF, or use Byte.toUnsignedInt.
  • A negative constant in Go. The specification lists uint(-1) as an illegal constant expression: "-1 cannot be represented as a uint"6. A conversion of a variable that holds -1 compiles and wraps.
  • A narrowing cast in C. A conversion to a signed type that cannot hold the value is implementation-defined5. Test the range before the conversion.

Cost

The choice of signedness does not change the speed of most operations. Wikipedia says that with two's complement, "the fundamental arithmetic operations of addition, subtraction, and multiplication are identical to those for unsigned binary numbers"17. The difference is in what the processor reports: "arithmetic instructions usually set different CPU flags such as the carry flag for unsigned arithmetic and the overflow flag for signed."1 Comparison, division, right shift and widening conversion have separate signed and unsigned forms, but each form is one instruction on common processors.

The style guides choose by meaning, not by speed. The C++ Core Guidelines say "ES.101: Use unsigned types for bit manipulation" and "ES.102: Use signed types for arithmetic"15. The Google C++ Style Guide says: "Unsigned integers are good for representing bitfields and modular arithmetic."16

History

Java has no unsigned integral type other than char10. Java version 1.8 added unsigned methods to Integer, such as compareUnsigned, divideUnsigned and toUnsignedString, each marked "Since: 1.8"11. C++20 added the functions std::cmp_less and its relatives9, and Rust 1.87.0 added cast_unsigned14.

References

  1. Signedness, Wikipedia, the introduction; In programming languages
  2. Data Types, The Rust Programming Language, Integer Types
  3. Integral numeric types, C# reference, Characteristics of the integral types
  4. Operator expressions, The Rust Reference, Numeric cast
  5. Implicit conversions, C reference, cppreference.com, Usual arithmetic conversions; Integer conversions
  6. The Go Programming Language Specification, Numeric types; Conversions between numeric types; Constant expressions
  7. Arithmetic operators, C# reference, the introduction
  8. Built-in Types, Python documentation, Numeric Types; int.to_bytes()
  9. std::cmp_equal, cmp_not_equal, cmp_less, cmp_greater, cmp_less_equal, cmp_greater_equal, cppreference.com, the description
  10. The Java Language Specification, Java SE 27 Edition, Chapter 4, 4.2 Primitive Types and Values
  11. Integer (Java SE 27 and JDK 27), compareUnsigned; divideUnsigned; toUnsignedString
  12. Unsigned right shift (>>>), MDN Web Docs, the introduction; Description; Examples
  13. Arithmetic types, C reference, cppreference.com, Character types
  14. Primitive Type i32, The Rust Standard Library, cast_unsigned; unsigned_abs
  15. C++ Core Guidelines, ES.100, ES.101, ES.102, ES.106, ES.107
  16. Google C++ Style Guide, Integer Types; On Unsigned Integers
  17. Two's complement, Wikipedia, the introduction

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/AV46E1/text.yaml