Course contents 02 / 32

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 ww-bit vector is written x=xw−1xw−2…x1x0x = x_{w-1} x_{w-2} \dots x_1 x_0, with xw−1x_{w-1} the most significant bit and x0x_0 the least significant. U(x)U(x) is its value read as an unsigned integer and T(x)T(x) its value read in two’s complement. xˉ\bar x is the bitwise complement (every bit flipped). A subscript gives the base where it matters: 101121011_2, 0x2C=2C160\text{x}2\text{C} = 2\text{C}_{16}. 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:

U(x)=∑i=0w−1xi 2i,e.g. U(1011002)=32+8+4=44.\begin{gathered} U(x) = \sum_{i=0}^{w-1} x_i\, 2^i , \\ \text{e.g. } U(101100_2) = 32 + 8 + 4 = 44 . \end{gathered}

With ww bits there are 2w2^w patterns, and UU maps them one-to-one onto 0,1,…,2w−10, 1, \dots, 2^w - 1. 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: 0010 110020010\ 1100_2 is 0x2C, and 2⋅16+12=442 \cdot 16 + 12 = 44. 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 ww-bit adder keeps only ww bits of the result and drops the final carry, so it computes

(a+b) mod 2w.(a + b) \bmod 2^w .

When the true sum is at least 2w2^w, the result wraps around: in 4 bits, 11012+00112=1 000021101_2 + 0011_2 = 1\,0000_2, and the adder returns 00000000, so 13+313 + 3 gives 00. Unsigned arithmetic is arithmetic modulo 2w2^w: 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, 01010101 is +5+5 and 11011101 is −5-5.

It works for writing numbers down, and it breaks as soon as we compute:

  • Two zeros. 00000000 is +0+0 and 10001000 is −0-0. Every comparison with zero must check both.
  • A separate adder. Feed +5+5 and −5-5 to the unsigned adder: 0101+1101=1 00100101 + 1101 = 1\,0010, which keeps 0010=+20010 = +2, not 00. 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 xx is

 T(x)=−xw−1 2w−1+∑i=0w−2xi 2i \boxed{\,T(x) = -x_{w-1}\, 2^{w-1} + \sum_{i=0}^{w-2} x_i\, 2^i\,}

Comparing with U(x)U(x), which gives the top bit the weight +2w−1+2^{w-1}:

T(x)=U(x)−xw−1 2w,so  T(x)≡U(x)(mod2w).\begin{gathered} T(x) = U(x) - x_{w-1}\, 2^{w} , \\ \text{so}\ \ T(x) \equiv U(x) \pmod{2^w} . \end{gathered}

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 2w2^w. The range is

−2w−1≤T(x)≤2w−1−1,-2^{w-1} \le T(x) \le 2^{w-1} - 1 ,

one more negative number than positive, because zero takes one of the patterns with top bit 0. For 8 bits that is −128-128 to 127127; for 32 bits, −2,147,483,648-2{,}147{,}483{,}648 to 2,147,483,6472{,}147{,}483{,}647, about ±2.1×109\pm 2.1 \times 10^9; for 64 bits, about ±9.2×1018\pm 9.2 \times 10^{18}. The pattern of all ones is −1-1, and the pattern 1000…01000\dots0 is the most negative number.

Worked example. The byte 0xD6 =1101 01102= 1101\,0110_2. Unsigned: 128+64+16+4+2=214128 + 64 + 16 + 4 + 2 = 214. Two’s complement: the top bit weighs −128-128, so −128+64+16+4+2=−42-128 + 64 + 16 + 4 + 2 = -42, which is 214−256214 - 256, as the formula says.

Figure

The sixteen 4-bit patterns on a circle, read two ways

A circle of 4-bit unsigned and signed valuesSixteen bit patterns around a circle, 0000 at the top. Inside, the numbers 0 to 15; outside, 0 to 7 and then −8 to −1. A blue bar between 1111 and 0000 marks the unsigned seam, a red bar between 0111 and 1000 the signed seam.00000000011100102200113301004401015501106601117710008−810019−7101010−6101111−5110012−4110113−3111014−2111115−1+1: one step clockwiseunsigned wraps:15 + 1 → 0signed overflow:7 + 1 → −8inside: unsignedoutside: two's complementA circle of 4-bit unsigned and signed valuesSixteen bit patterns around a circle, 0000 at the top. Inside, the numbers 0 to 15; outside, 0 to 7 and then −8 to −1. A blue bar between 1111 and 0000 marks the unsigned seam, a red bar between 0111 and 1000 the signed seam.00000000011100102200113301004401015501106601117710008−810019−7101010−6101111−5110012−4110113−3111014−2111115−1+1: one step clockwiseunsigned wraps:15 + 1 → 0signed overflow:7 + 1 → −8inside: unsignedoutside: two's complement
The patterns 0000 to 1111 around a circle; adding one moves one step clockwise, and a 4-bit adder counts modulo 16. Blue numbers inside are the unsigned values, red numbers outside the two's complement values (the top bit weighs −8). Each reading has one seam: unsigned between 1111 and 0000 (15 + 1 gives 0), signed between 0111 and 1000 (7 + 1 gives −8). Away from its seam each reading goes up by one per step, so one adder serves both.

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 11111111 and 00000000; the signed reading (outside) jumps from +7+7 to −8-8 between 01110111 and 10001000. 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 ww-bit pattern xx and its complement xˉ\bar x. In each column exactly one of the two bits is 1, so the column sum is 1 and no carry ever arises:

x+xˉ=11…12⏟w ones=2w−1column by column, no carriesxˉ+1=2w−U(x)subtract U(x) and add 1 on both sides≡−U(x)≡−T(x)(mod2w)2w≡0, and T≡U.\begin{aligned} x + \bar x &= \underbrace{11\dots1_2}_{w\ \text{ones}} = 2^w - 1 && \text{column by column, no carries} \\ \bar x + 1 &= 2^w - U(x) && \text{subtract } U(x) \text{ and add 1 on both sides} \\ &\equiv -U(x) \equiv -T(x) \pmod{2^w} && 2^w \equiv 0, \text{ and } T \equiv U . \end{aligned}

So the bit pattern xˉ+1\bar x + 1, computed by the ww-bit adder, is congruent to −T(x)-T(x) modulo 2w2^w. Two patterns that are congruent modulo 2w2^w are the same pattern, and if −T(x)-T(x) lies in the range, it is the two’s complement pattern of −T(x)-T(x):

 −x=xˉ+1 \boxed{\,-x = \bar x + 1\,}

Worked example. 42=0010 1010242 = 0010\,1010_2. Inverting gives 1101 010121101\,0101_2, and adding one gives 1101 01102=1101\,0110_2 = 0xD6, which the previous example read as −42-42. Negating 0xD6 the same way returns 0010 10102=420010\,1010_2 = 42. Two edge cases follow from the range: −0=0ˉ+1=11…1+1=0-0 = \bar 0 + 1 = 11\dots1 + 1 = 0, a single zero; and the most negative number has no positive partner, so in 8 bits −(−128)-(-128) gives 1000 0000‾+1=0111 1111+1=1000 0000\overline{1000\,0000} + 1 = 0111\,1111 + 1 = 1000\,0000, which is −128-128 again.

Subtraction needs no circuit of its own: a−b=a+bˉ+1a - b = a + \bar b + 1, the adder with bb inverted and a carry of 1 into the lowest column.

Overflow and wraparound#

A ww-bit result that does not fit is not an error to the hardware. The adder returns the low ww bits, and what that means depends on the reading.

  • Unsigned overflow happens when the true sum is 2w2^w or more; the result is the sum minus 2w2^w. It shows up as a carry out of the top column.
  • Signed overflow happens when the true sum lies outside [−2w−1,2w−1−1][-2^{w-1}, 2^{w-1} - 1]. 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:

BitsUnsignedSigned
0111+0001=10000111 + 0001 = 10007+1=87 + 1 = 8, correct7+1=−87 + 1 = -8, overflow: two positives gave a negative
1101+0011=00001101 + 0011 = 0000, carry out13+3=013 + 3 = 0, overflow: wrapped−3+3=0-3 + 3 = 0, 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 2w2^w (§6.2.5): UINT_MAX + 1u is 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 > x for an int x is always true under that assumption, so clang -O2 replaces the comparison with 1, while clang -O0 computes the wrapped sum and, for x = 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=undefined reports such overflows at run time.
  • Converting a signed value to an unsigned type is defined modulo 2w2^w (§6.3.1.3): (unsigned)-1 is UINT_MAX. When a comparison mixes int and unsigned, the int is converted, so -1 < 0u is 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 s=xw−1s = x_{w-1}:
T(s xw−1…x0)=−s 2w+s 2w−1+∑i=0w−2xi 2ithe old top bit now weighs +2w−1=−s 2w−1+∑i=0w−2xi 2i−2w+2w−1=−2w−1=T(xw−1…x0),\begin{aligned} T(s\, x_{w-1} \dots x_0) &= -s\, 2^{w} + s\, 2^{w-1} + \sum_{i=0}^{w-2} x_i\, 2^i && \text{the old top bit now weighs } +2^{w-1} \\ &= -s\, 2^{w-1} + \sum_{i=0}^{w-2} x_i\, 2^i && -2^w + 2^{w-1} = -2^{w-1} \\ &= T(x_{w-1} \dots x_0) , && \end{aligned}

and repeating the step adds as many bits as needed.

Worked example. The 4-bit pattern 10111011 is −5-5 in two’s complement and 11 unsigned. Sign-extended to 8 bits it is 1111 1011=1111\,1011 = 0xFB, still −5-5; zero-extended it is 0000 1011=110000\,1011 = 11. 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 kk bits and drops the rest. It computes the value modulo 2k2^k, 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 nn: 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. 0101 1000&0101 0111=0101 00000101\,1000 \mathbin{\&} 0101\,0111 = 0101\,0000.

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 kk positions.

  • A left shift x << k fills with zeros on the right and drops bits on the left. It multiplies by 2k2^k modulo 2w2^w.
  • A logical right shift fills with zeros on the left. For an unsigned value it is division by 2k2^k rounded down: ⌊U(x)/2k⌋\lfloor U(x)/2^k \rfloor.
  • 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 ⌊T(x)/2k⌋\lfloor T(x)/2^k \rfloor, rounded toward −∞-\infty.

Worked example. The byte 1000 101021000\,1010_2, 138 unsigned and −118-118 signed:

OperationResultValue
<< 10001 01000001\,0100276 mod 256=20276 \bmod 256 = 20
logical >> 20010 00100010\,001034=⌊138/4⌋34 = \lfloor 138/4 \rfloor
arithmetic >> 21110 00101110\,0010−30=⌊−118/4⌋=⌊−29.5⌋-30 = \lfloor -118/4 \rfloor = \lfloor -29.5 \rfloor

C’s division rounds toward zero, so -118 / 4 is −29-29, not −30-30: 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.

Figure

Byte order: the word 0x12345678 at address 0x100

The bytes of a word in memory in the two byte ordersA register holding the bytes 12 34 56 78. Below, two rows of memory at addresses 0x100 to 0x103: big-endian holds 12 34 56 78, little-endian holds 78 56 34 12. Under the rows, loading the byte at 0x100 gives 0x12 and 0x78 respectively.the word 0x12345678 in a registermost significant byteleast significant byte123456781big-endian: MSB first0x100120x101340x102560x103782little-endian: RISC-V, x86, ARM0x100780x101560x102340x103123lbu from 0x100 → 0x12lbu from 0x100 → 0x784The bytes of a word in memory in the two byte ordersA register holding the bytes 12 34 56 78. Below, two rows of memory at addresses 0x100 to 0x103: big-endian holds 12 34 56 78, little-endian holds 78 56 34 12. Under the rows, loading the byte at 0x100 gives 0x12 and 0x78 respectively.the word 0x12345678 in a registerMSBLSB123456781big-endian: MSB first0x100120x101340x102560x103782little-endian: RISC-V, x86, ARM0x100780x101560x102340x103123lbu from 0x100 → 0x12lbu from 0x100 → 0x784
Top: the word in a register, with the most significant byte 0x12 in blue and the least significant byte 0x78 in red. Big-endian stores the most significant byte at the lowest address, so memory holds the bytes in the order we write the number (2). Little-endian, used by RISC-V, x86 and ARM, stores the least significant byte at the lowest address (3). Loading one byte from the address of the word, 0x100, therefore gives 0x12 in one case and 0x78 in the other (4).
  1. The word 0x12345678 in a register has a most significant byte 0x12 and a least significant byte 0x78.
  2. A big-endian machine stores the most significant byte at the lowest address: at addresses 0x100 to 0x103 it writes 12 34 56 78, the order in which we write the number.
  3. A little-endian machine stores the least significant byte at the lowest address: 78 56 34 12.
  4. Loading one byte from the address of the word therefore gives 0x78 on a little-endian machine and 0x12 on 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 dd 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 pointsBytesBit pattern
0x00–0x7F10xxxxxxx
0x80–0x7FF2110xxxxx 10xxxxxx
0x800–0xFFFF31110xxxx 10xxxxxx 10xxxxxx
0x10000–0x10FFFF411110xxx 10xxxxxx 10xxxxxx 10xxxxxx

Worked example. 'Ж' is code point 0x416 =100 0001 01102= 100\,0001\,0110_2, eleven bits, so two bytes: 110 + the top five bits 1000010000 gives 0xD0, and 10 + the low six bits 010110010110 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 nn-th character is no longer at byte nn, 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#

UnsignedSign and magnitude (baseline)Two’s complement
Range, ww bits0…2w−10 \dots 2^w - 1−(2w−1−1)…2w−1−1-(2^{w-1} - 1) \dots 2^{w-1} - 1−2w−1…2w−1−1-2^{w-1} \dots 2^{w-1} - 1
Zerosonetwo, +0+0 and −0-0one
Additionthe ww-bit addera separate circuit for mixed signsthe same ww-bit adder
Negationflip the sign bitinvert all bits, add 1
Wideningzero extensionmove the sign bitsign extension
Overflowcarry out of the top bitoperands 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 0.10.1 nor 103010^{30} fits in a 32-bit integer; the next note is about that.

What you should remember#

  • ww bits give 2w2^w patterns. Unsigned: 0…2w−10 \dots 2^w - 1. Two’s complement: the top bit weighs −2w−1-2^{w-1}, range −2w−1…2w−1−1-2^{w-1} \dots 2^{w-1} - 1.
  • T(x)≡U(x)(mod2w)T(x) \equiv U(x) \pmod{2^w}, so one adder serves both readings; −x=xˉ+1-x = \bar x + 1 because x+xˉ=2w−1x + \bar x = 2^w - 1.
  • 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. lb versus lbu.
  • Left shift multiplies by 2k2^k; logical right shift divides unsigned values; arithmetic right shift divides signed values rounding toward −∞-\infty.
  • 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 ±2×109\pm 2 \times 10^9 in steps of 1, and they cannot hold 0.10.1, π\pi or the mass of an electron. The next note builds numbers that cover 10−3810^{-38} to 103810^{38} 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.