02 / 32 · Foundations
Bits, integers and byte order
How a computer stores integers and text in bits: binary and hexadecimal, unsigned and two's complement integers, why negation is invert-plus-one, overflow and wraparound in C and RISC-V, sign extension, bitwise operations and shifts, byte order, ASCII and UTF-8.
On this page 10
The previous note ended with a memory that holds only numbers: the instruction 0x00B50633, the integers 5 and 7, the 13 bytes of "hello, world\n". A memory cell does not hold the number 5, though. It holds a few dozen electrical states, each high or low, and the number is an interpretation of them. This note sets out the interpretations that every later note relies on: how bits make unsigned integers, how the same bits can mean a negative number so that one adder serves both, what happens when a result does not fit, how bits are combined and shifted, in which order the bytes of a word lie in memory, and how characters become bytes.
Notation. A -bit vector is written , with the most significant bit and the least significant. is its value read as an unsigned integer and its value read in two’s complement. is the bitwise complement (every bit flipped). A subscript gives the base where it matters: , . In C and assembly, 0x marks hexadecimal and 0b binary.
Bits, bytes and hexadecimal#
A digital circuit represents a bit as a voltage that is either near zero or near the supply voltage. Two levels are far apart, so noise that shifts a voltage a little does not change the bit, and the circuits that store and switch two levels are simple. Everything else is built from bits by agreeing on an interpretation.
A sequence of bits is a number in base 2, with weights that double from right to left:
With bits there are patterns, and maps them one-to-one onto . A byte is 8 bits, the smallest unit with its own address in memory. A word is the natural unit of a processor: 32 bits in RV32, the base RISC-V instruction set used in this course, and 64 bits in RV64.
Binary is long to write, so we group bits by four. Each group of four, a nibble, is one hexadecimal digit, 0–9 then A–F for 10–15. Conversion is a table lookup in both directions: is 0x2C, and . A byte is exactly two hex digits and a 32-bit word eight, which is why addresses and machine words are written in hex: 0x00B50633 is a 32-bit pattern whose bits can be read off digit by digit.
The sizes of the C integer types are not fixed by the language, only their minimum ranges. On the 64-bit Linux and macOS systems used later in the course, char is 1 byte, short 2, int 4, long 8 and a pointer 8 (the LP64 model); on 32-bit RISC-V (ILP32) long and pointers are 4 bytes; on 64-bit Windows long stays 4 bytes. When the width matters, C programs use <stdint.h>: int8_t, uint32_t, int64_t.
Unsigned integers and their arithmetic#
Addition of unsigned numbers is the school algorithm in base 2: add column by column from the right, carrying 1 into the next column when a column sums to 2 or 3. A -bit adder keeps only bits of the result and drops the final carry, so it computes
When the true sum is at least , the result wraps around: in 4 bits, , and the adder returns , so gives . Unsigned arithmetic is arithmetic modulo : the numbers sit on a circle, not on a line.
Baseline: a sign bit in front#
The simplest way to represent negative numbers is the one used on paper: reserve the top bit for the sign and keep the magnitude in the rest. In 4-bit sign and magnitude, is and is .
It works for writing numbers down, and it breaks as soon as we compute:
- Two zeros. is and is . Every comparison with zero must check both.
- A separate adder. Feed and to the unsigned adder: , which keeps , not . Adding numbers of opposite signs needs a subtraction of magnitudes and a decision about which is larger, so the hardware needs different circuits for signed and unsigned numbers.
Sign and magnitude survives where those costs do not matter, notably in the sign bit of floating-point numbers, the subject of the next note. For integers, every modern processor uses a better idea.
Two’s complement#
The two’s complement value of is
Comparing with , which gives the top bit the weight :
Patterns with the top bit 0 mean the same in both readings; patterns with the top bit 1 are negative, and their signed value is the unsigned value minus . The range is
one more negative number than positive, because zero takes one of the patterns with top bit 0. For 8 bits that is to ; for 32 bits, to , about ; for 64 bits, about . The pattern of all ones is , and the pattern is the most negative number.
Worked example. The byte 0xD6 . Unsigned: . Two’s complement: the top bit weighs , so , which is , as the formula says.
The sixteen 4-bit patterns on a circle, read two ways
The figure puts the 16 patterns of 4 bits on a circle. Adding 1 moves one step clockwise. The unsigned reading (inside) jumps from 15 back to 0 between and ; the signed reading (outside) jumps from to between and . Away from those two seams both readings count up by one, which is why the same circuit serves both.
Why negation is invert-plus-one#
Take any -bit pattern and its complement . In each column exactly one of the two bits is 1, so the column sum is 1 and no carry ever arises:
So the bit pattern , computed by the -bit adder, is congruent to modulo . Two patterns that are congruent modulo are the same pattern, and if lies in the range, it is the two’s complement pattern of :
Worked example. . Inverting gives , and adding one gives 0xD6, which the previous example read as . Negating 0xD6 the same way returns . Two edge cases follow from the range: , a single zero; and the most negative number has no positive partner, so in 8 bits gives , which is again.
Subtraction needs no circuit of its own: , the adder with inverted and a carry of 1 into the lowest column.
Overflow and wraparound#
A -bit result that does not fit is not an error to the hardware. The adder returns the low bits, and what that means depends on the reading.
- Unsigned overflow happens when the true sum is or more; the result is the sum minus . It shows up as a carry out of the top column.
- Signed overflow happens when the true sum lies outside . Adding two numbers of opposite signs can never overflow, because the sum lies between them. Adding two numbers of the same sign overflows exactly when the result has the other sign.
Worked example. Two 4-bit additions, each read both ways:
| Bits | Unsigned | Signed |
|---|---|---|
| , correct | , overflow: two positives gave a negative | |
| , carry out | , overflow: wrapped | , correct |
The same bits overflow in one reading and are correct in the other. The hardware cannot know which reading the program intends, so it produces the bits and leaves the interpretation to the instructions that follow.
In RISC-V. The base instruction set has no overflow flag and never traps on overflow: add, addi and sub write the low 32 bits of the result (RISC-V Unprivileged ISA, RV32I chapter). A program that cares checks with a branch. For unsigned addition one extra instruction suffices, because the sum wrapped exactly when it is smaller than an operand: add t0, t1, t2 then bltu t0, t1, overflow. Signed addition takes three extra instructions in general (the Code section runs the unsigned check).
In C the two readings follow different rules, set by the C standard (ISO C17):
- Unsigned arithmetic is defined to wrap modulo (§6.2.5):
UINT_MAX + 1uis 0. - Signed overflow is undefined behaviour (§6.5): the standard places no requirement on what happens. The compiler is allowed to assume it never occurs, and optimizers do.
x + 1 > xfor anint xis always true under that assumption, soclang -O2replaces the comparison with 1, whileclang -O0computes the wrapped sum and, forx = INT_MAX, returns 0 (the Code section shows both). A program whose correctness depends on signed wraparound is wrong, even if it happens to work at one optimization level.-fsanitize=undefinedreports such overflows at run time. - Converting a signed value to an unsigned type is defined modulo (§6.3.1.3):
(unsigned)-1isUINT_MAX. When a comparison mixesintandunsigned, theintis converted, so-1 < 0uis false. Converting an out-of-range value to a signed type is implementation-defined.
Sign and zero extension#
Loading a byte into a 32-bit register, or passing a short where an int is expected, needs a wider pattern with the same value.
- Zero extension fills the new high bits with zeros. It preserves the unsigned value, since the new bits weigh nothing.
- Sign extension fills the new high bits with copies of the top bit. It preserves the two’s complement value. For one new bit, with :
and repeating the step adds as many bits as needed.
Worked example. The 4-bit pattern is in two’s complement and 11 unsigned. Sign-extended to 8 bits it is 0xFB, still ; zero-extended it is . RISC-V has both kinds of byte and halfword load: lb and lh sign-extend, lbu and lhu zero-extend. In C the type decides: converting an int8_t to a wider type sign-extends, converting a uint8_t zero-extends.
The opposite operation, truncation, keeps the low bits and drops the rest. It computes the value modulo , which changes any value that does not fit: the 32-bit 0x00000100 (256) truncated to a byte is 0.
Bitwise operations and shifts#
Bitwise operators apply a logical operation to each column independently: AND (&) gives 1 where both bits are 1, OR (|) where at least one is, XOR (^) where exactly one is, and NOT (~) flips every bit. They are the tools for treating a word as a set of flags or packed fields:
- set bit :
x | (1 << n); clear it:x & ~(1 << n); test it:(x >> n) & 1; - extract a field: shift it down and mask it, as the floating-point note does to take a float apart;
x & (x - 1)clears the lowest set bit: subtracting 1 turns the lowest 1 into 0 and the zeros below it into ones, and the AND removes them all. .
C also has logical operators &&, || and !, which treat a whole value as true (nonzero) or false (zero), return 0 or 1, and skip evaluating the right operand when the left one decides the result. 0x69 & 0x55 is 0x41, while 0x69 && 0x55 is 1.
Shifts move all bits left or right by positions.
- A left shift
x << kfills with zeros on the right and drops bits on the left. It multiplies by modulo . - A logical right shift fills with zeros on the left. For an unsigned value it is division by rounded down: .
- An arithmetic right shift fills with copies of the top bit, so a negative number stays negative. For a two’s complement value it computes , rounded toward .
Worked example. The byte , 138 unsigned and signed:
| Operation | Result | Value |
|---|---|---|
<< 1 | ||
logical >> 2 | ||
arithmetic >> 2 |
C’s division rounds toward zero, so -118 / 4 is , not : a compiler cannot replace a signed division by a power of two with a plain arithmetic shift, and adds a correction for negative operands.
RISC-V has all three shifts, sll, srl and sra, with immediate forms slli, srli, srai; on RV32 only the low 5 bits of the shift amount are used. In C, >> on an unsigned value is logical; on a negative signed value it is implementation-defined, and the common compilers, including clang and GCC, make it arithmetic. Shifting by a negative amount or by the width of the type or more is undefined behaviour (§6.5.7).
Byte order#
A 32-bit word occupies four bytes, at four consecutive addresses. Which byte goes where is a convention, called endianness.
Byte order: the word 0x12345678 at address 0x100
- The word
0x12345678in a register has a most significant byte0x12and a least significant byte0x78. - A big-endian machine stores the most significant byte at the lowest address: at addresses
0x100to0x103it writes12 34 56 78, the order in which we write the number. - A little-endian machine stores the least significant byte at the lowest address:
78 56 34 12. - Loading one byte from the address of the word therefore gives
0x78on a little-endian machine and0x12on a big-endian one.
Both conventions work, and neither is faster; the choice matters only when the same bytes are viewed both as a word and as separate bytes, or when data moves between machines. x86, ARM in the common operating systems, and RISC-V systems in practice are little-endian. The RISC-V specification allows big-endian and bi-endian implementations, but its designers chose little-endian as the default because little-endian systems dominate commercially, and RISC-V instructions are always stored as little-endian 16-bit parcels whatever the data byte order (RISC-V Unprivileged ISA, §1.5). RARS and Linux on RISC-V are little-endian. Internet protocols send multi-byte numbers in big-endian order, called network byte order, and C programs convert with htonl and ntohl, which the sockets note uses.
Endianness concerns bytes within a multi-byte value, never bits within a byte, and never the order of elements in an array: int a[2] keeps a[0] at the lower address on every machine. A C program sees it by looking at a word through a byte pointer: the bytes of uint32_t w = 0x12345678, read through an unsigned char * from the lowest address up, are 78 56 34 12 on an Apple M1 (the Code section).
Characters: ASCII and UTF-8#
Text is numbers too. ASCII assigns the numbers 0–127 to the English letters, digits, punctuation and control characters: 'A' is 65 = 0x41, 'a' is 97 = 0x61, '0' is 48 = 0x30, the newline '\n' is 10 = 0x0A. The layout has useful regularities: the digit is '0' + d, and an upper-case letter differs from its lower-case one only in bit 5 (0x20). The 13 bytes of "hello, world\n" are 68 65 6c 6c 6f 2c 20 77 6f 72 6c 64 0a. A C string is such a sequence of char followed by a zero byte, which marks its end; the memory-allocation note returns to strings.
ASCII covers one alphabet. Unicode assigns a number, a code point, to every character of every script, up to 0x10FFFF, and UTF-8 stores each code point in 1 to 4 bytes. The first byte says how many bytes follow, and every continuation byte starts with 10:
| Code points | Bytes | Bit pattern |
|---|---|---|
0x00–0x7F | 1 | 0xxxxxxx |
0x80–0x7FF | 2 | 110xxxxx 10xxxxxx |
0x800–0xFFFF | 3 | 1110xxxx 10xxxxxx 10xxxxxx |
0x10000–0x10FFFF | 4 | 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx |
Worked example. 'Ж' is code point 0x416 , eleven bits, so two bytes: 110 + the top five bits gives 0xD0, and 10 + the low six bits gives 0x96. The euro sign 0x20AC takes three bytes, E2 82 AC, and an emoji such as 0x1F600 four.
ASCII text is valid UTF-8 unchanged, and since UTF-8 is a sequence of bytes, it has no byte-order problem. The cost is that the -th character is no longer at byte , and a string’s length in bytes differs from its number of characters, a distinction the NLP course’s note on text follows into tokenization.
What changed#
| Unsigned | Sign and magnitude (baseline) | Two’s complement | |
|---|---|---|---|
| Range, bits | |||
| Zeros | one | two, and | one |
| Addition | the -bit adder | a separate circuit for mixed signs | the same -bit adder |
| Negation | flip the sign bit | invert all bits, add 1 | |
| Widening | zero extension | move the sign bit | sign extension |
| Overflow | carry out of the top bit | operands of one sign, result of the other |
Limitations#
- Fixed width. Every integer type has a range, and leaving it is silent in hardware: RISC-V has no flag and no trap. Languages differ in what they do about it: Python switches to arbitrary-precision integers, C wraps unsigned values and leaves signed overflow undefined.
- Bits carry no type. The same 32 bits are an unsigned number, a signed number, four characters, an instruction or a float. Only the instruction that uses them decides, so a wrong interpretation is a silent bug.
- Byte order leaks through any byte-level view of memory: files, network packets, casts between pointer types.
- Integers cover a narrow, evenly spaced range. Neither nor fits in a 32-bit integer; the next note is about that.
What you should remember#
- bits give patterns. Unsigned: . Two’s complement: the top bit weighs , range .
- , so one adder serves both readings; because .
- Overflow is silent. Unsigned: carry out. Signed: same-sign operands give a result of the other sign. In C, unsigned wraps; signed overflow is undefined behaviour.
- Sign extension copies the top bit and preserves the signed value; zero extension preserves the unsigned value.
lbversuslbu. - Left shift multiplies by ; logical right shift divides unsigned values; arithmetic right shift divides signed values rounding toward .
- Little-endian stores the least significant byte at the lowest address. RISC-V systems, x86 and ARM in practice are little-endian; network byte order is big-endian.
- ASCII is 7-bit; UTF-8 encodes every Unicode code point in 1–4 bytes and contains ASCII unchanged.
Code#
Two’s complement in Python, with the worked examples of the note. Python’s integers have no fixed width, so the functions take the width from the bit string:
def unsigned(bits): # the bit string read as an unsigned number
return int(bits, 2)
def signed(bits): # two's complement: the top bit weighs -2^(w-1)
w = len(bits)
return unsigned(bits) - (int(bits[0]) << w)
def encode(v, w): # the w-bit pattern of v, taken modulo 2^w
return format(v % (1 << w), f'0{w}b')
print(unsigned('11010110'), signed('11010110'), hex(unsigned('11010110'))) # 214 -42 0xd6
x = encode(42, 8)
inv = ''.join('1' if b == '0' else '0' for b in x)
print(x, inv, encode(unsigned(inv) + 1, 8), signed(encode(unsigned(inv) + 1, 8))) # 00101010 11010101 11010110 -42
print(encode(-128, 8), encode(-(-128), 8)) # 10000000 10000000: -(-128) wraps to -128
for a, b in (('0111', '0001'), ('1101', '0011')): # 4-bit additions
s = encode(unsigned(a) + unsigned(b), 4)
print(a, '+', b, '=', s, '| unsigned', unsigned(a), '+', unsigned(b), '->', unsigned(s),
'| signed', signed(a), '+', signed(b), '->', signed(s))
# 0111 + 0001 = 1000 | unsigned 7 + 1 -> 8 | signed 7 + 1 -> -8
# 1101 + 0011 = 0000 | unsigned 13 + 3 -> 0 | signed -3 + 3 -> 0
v = '1011'
print(v[0] * 4 + v, signed(v[0] * 4 + v), '0000' + v, unsigned('0000' + v)) # 11111011 -5 00001011 11
x = '10001010'
print(unsigned(x), signed(x)) # 138 -118
print(encode(unsigned(x) << 1, 8), '0' * 2 + x[:-2], x[0] * 2 + x[:-2]) # 00010100 00100010 11100010
print(unsigned('00100010'), signed('11100010'), -118 // 4, int(-118 / 4)) # 34 -30 -30 -29
print(format(0b01011000 & (0b01011000 - 1), '08b')) # 01010000
for ch in 'A', 'a', '0', 'Ж', '€', '😀':
print(ch, hex(ord(ch)), ch.encode('utf-8').hex(' '))
# A 0x41 41 | a 0x61 61 | 0 0x30 30 | Ж 0x416 d0 96 | € 0x20ac e2 82 ac | 😀 0x1f600 f0 9f 98 80
print((0x12345678).to_bytes(4, 'little').hex(' '), (0x12345678).to_bytes(4, 'big').hex(' ')) # 78 56 34 12 12 34 56 78
The same facts in C, compiled with clang -std=c17 -Wall -Wextra -O0. The first line of output shows the byte order of the machine; the comments give the output on an Apple M1, which is little-endian, as is every machine this course uses:
#include <limits.h>
#include <stdint.h>
#include <stdio.h>
static void show_bytes(const void *p, size_t n) { /* the bytes of an object, lowest address first */
const unsigned char *b = p;
for (size_t i = 0; i < n; i++)
printf("%02x ", b[i]);
printf("\n");
}
int main(void) {
uint32_t word = 0x12345678;
show_bytes(&word, sizeof word); /* 78 56 34 12: little-endian */
show_bytes("hello, world\n", 13); /* 68 65 6c 6c 6f 2c 20 77 6f 72 6c 64 0a */
int8_t x = 42;
printf("%d %d\n", (int8_t)(~x + 1), -x); /* -42 -42: invert and add one */
printf("%u %u\n", UINT_MAX + 1u, (unsigned)-1); /* 0 4294967295: unsigned arithmetic wraps modulo 2^32 */
printf("%d\n", -1 < 0u); /* 0: -1 is converted to unsigned, 4294967295 */
int8_t neg5 = -5; /* bits 1111 1011 */
printf("%d %d\n", (int16_t)neg5, (uint8_t)neg5); /* -5 251: sign extension; the same bits read as unsigned */
printf("%d %d\n", -118 >> 2, -118 / 4); /* -30 -29: arithmetic shift floors, division truncates */
printf("%u\n", 0x8Au >> 2); /* 34: logical shift of an unsigned value */
printf("%zu %zu %zu %zu\n", sizeof(short), sizeof(int), sizeof(long), sizeof(void *)); /* 2 4 8 8 on 64-bit macOS and Linux */
return 0;
}
Signed overflow is undefined behaviour, and the optimizer uses that. The same file gives different answers at two optimization levels; this is the one block in the note compiled three ways, each shown in the comments:
#include <limits.h>
#include <stdio.h>
int grows(int x) { return x + 1 > x; } /* always true, unless x + 1 overflows */
int main(void) {
printf("%d\n", grows(INT_MAX));
return 0;
}
/* clang -std=c17 -O0 ub.c -> 0 (the wrapped sum INT_MIN is not greater than INT_MAX)
clang -std=c17 -O2 ub.c -> 1 (overflow "cannot happen", so the comparison is folded to true)
clang -std=c17 -O0 -fsanitize=undefined ub.c -> "runtime error: signed integer overflow:
2147483647 + 1 cannot be represented in type 'int'", then 0 */
Byte order, sign extension and overflow in RV32I, in RARS syntax:
# Byte order, sign extension and overflow in RV32I
.data
word: .word 0x12345678
.text
main:
la t0, word
lbu a0, 0(t0) # the byte at the lowest address
li a7, 34 # 34 = print integer in hexadecimal
ecall # prints 0x00000078: RISC-V is little-endian
li a0, 10 # newline
li a7, 11
ecall
li t1, 0xFB # the byte 1111 1011
sb t1, 0(t0)
lb a0, 0(t0) # load byte, sign-extended
li a7, 1
ecall # prints -5
li a0, 32 # space
li a7, 11
ecall
lbu a0, 0(t0) # load byte, zero-extended
li a7, 1
ecall # prints 251
li a0, 10
li a7, 11
ecall
li t1, 0x7FFFFFFF # the largest 32-bit signed integer
addi a0, t1, 1 # wraps: no trap, no flag
li a7, 1
ecall # prints -2147483648
li a0, 10
li a7, 11
ecall
li t1, -1 # 0xFFFFFFFF, the largest unsigned value
li t2, 1
add t3, t1, t2 # unsigned overflow check from the specification:
bltu t3, t1, overflow # the sum is smaller than an operand exactly when it wrapped
li a0, 0
j print
overflow:
li a0, 1
print:
li a7, 1
ecall # prints 1
li a7, 10
ecall
Next#
Integers are exact but cover a narrow range at a fixed spacing: 32 bits reach about in steps of 1, and they cannot hold , or the mass of an electron. The next note builds numbers that cover to in the same 32 bits, by storing an exponent and a significand separately, as in scientific notation. It uses this note’s tools throughout: a biased exponent field, a sign bit in front, and shifts and masks to take a float apart bit by bit.
References#
- A. Tatarnikov. Computer Architecture and Operating Systems (HSE), lecture 2: data representation.
- R. E. Bryant, D. R. O’Hallaron. Computer Systems: A Programmer’s Perspective, 3rd ed. Pearson, 2016. §2.1 (information storage, hexadecimal, byte ordering), §2.2 (integer representations, two’s complement, sign extension, truncation), §2.3 (integer arithmetic and overflow).
- D. M. Harris, S. L. Harris. Digital Design and Computer Architecture, RISC-V Edition. Morgan Kaufmann, 2021. §1.4 (number systems, two’s complement, sign and zero extension).
- D. A. Patterson, J. L. Hennessy. Computer Organization and Design, RISC-V Edition, 2nd ed. Morgan Kaufmann, 2020. §2.4 (signed and unsigned numbers), §3.2 (addition, subtraction and overflow).
- A. Waterman, K. Asanović (eds.). The RISC-V Instruction Set Manual, Volume I: Unprivileged ISA. RISC-V International. §1.5 (memory and instruction byte order), RV32I chapter (integer computational instructions, overflow checks with branches, loads and stores).
- ISO/IEC 9899:2018, Programming languages — C (C17). §6.2.5 (unsigned arithmetic wraps), §6.3.1.3 (signed and unsigned conversions), §6.5 (exceptional conditions are undefined), §6.5.7 (shift operators). The final draft N2176 is freely available.
- The Unicode Consortium. The Unicode Standard, §3.9 (UTF-8 encoding form); F. Yergeau, RFC 3629: UTF-8, a transformation format of ISO 10646, 2003.