Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 2 (Aug 27), slide deck
02-bits-bytes-ints. Reading: CS:APP3e §2.1–2.3 (plus §2.4 for the floating-point supplement in §9). Lab: L1 (datalab) is handed out. Sources: the public Fall 2026 slides and CS:APP. The seven demos and all their numbers were written for these notes and run on the author’s machine (Apple M4 Pro, arm64, clang 21). Themake asmlistings were also cross-compiled for x86-64. Code:code/lecture02/. Reading time: ~80 minutes; ~30 more to run and read the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Convert fluently between binary, hexadecimal and decimal, and say why programmers prefer hex.
- Use the bit-level operators
& | ^ ~ << >>and explain how they differ from the logical operators&& || !. - Write down the unsigned and two’s-complement interpretations of any bit pattern, and say why two’s complement beat sign-magnitude.
- Predict exactly what happens when C converts between signed and unsigned types, between widths, and in mixed comparisons. That includes the classic bugs.
- Explain why addition and multiplication are the same bit operation for signed and unsigned numbers, detect overflow, and turn multiplication and division by powers of two into shifts, rounding correctly.
- Read multi-byte values in memory dumps and disassembly on a little-endian machine.
0.2 Prerequisites and scope
- Lecture 1 (the “ints are not integers” reality) and basic C.
- In scope: CS:APP §2.1–2.3. Supplement: the IEEE float layout (§9). The 2026 lectures skip floating point, but Lab 1 and Lecture 1 rely on it.
- Not in scope: floating-point arithmetic and rounding modes in depth (CS:APP §2.4.4–2.4.6), and machine instructions (Lecture 3). The asm listings in §7.5 are a preview.
0.3 Section → code map
| Section | Idea | Demo in code/lecture02/ |
|---|---|---|
| §1–2 | why binary; hex; sizes of C types | (06 prints sizes and bytes) |
| §3 | Boolean algebra, bit vectors as sets, shifts | 01_bit_level_ops.c |
| §4 | unsigned, sign-magnitude, two’s complement | 02_encodings.c |
| §5 | casting signed ↔ unsigned, mixed comparisons | 03_casting.c |
| §6 | expanding (zero/sign extension), truncating | 04_extend_truncate.c |
| §7 | addition, overflow, multiplication, shifts as ×/÷ | 05_arithmetic.c (+ make asm) |
| §8 | byte ordering | 06_byte_order.c |
| §9 | supplement: IEEE float fields | 07_float_fields.c |
0.4 Notation
- w is the word width in bits. xi is bit i of x, with bit 0 the least significant.
- B2Uw, B2Tw: “binary to unsigned/two’s complement” for w bits. U2T, T2U: conversions between them.
- UMaxw = 2w − 1, TMinw = −2w−1, TMaxw = 2w−1 − 1.
- In binary strings,
_separates groups of 4 bits so they line up with hex digits:0110_1001=0x69.
1. Why bits?
1.1 Intuition: two states are easy, many states are hard
Before digital computers there were analog computers. A circuit could add voltages, and you read the answer off a meter. The trouble is precision. A voltage of 0.731 V picks up noise from every wire, every temperature change and every copying step, so you never get the exact value back.
Digital electronics asks a much easier question: is the voltage high enough to call it “on”, or low enough to call it “off”? A signal at 0.2 V or 0.9 V can only mean one thing if “off” is below about 0.3 V and “on” is above about 0.8 V. That is why every modern computer is binary: two states survive noise, can be regenerated perfectly at every stage, and can be copied billions of times without drift. One such two-state value is a bit.
1.2 Bits can encode anything countable
A single bit says little; a group of bits can name 2w different things. What they name is a convention:
- numbers: integers (this lecture) and approximations of reals (§9);
- characters: ASCII and UTF-8 text (
'A'=0x41); - instructions: the bytes
48 89 03are the x86-64 instructionmovq %rax,(%rbx)(Lecture 3); - anything enumerable: colors, keyboard keys, permissions, network packet types.
This is CS:APP chapter 1’s “information = bits + context” made concrete. If you can number it, you can store it in binary. The rest of this lecture is about the conventions for numbers.
1.3 Binary, place values, and the byte
Binary works like decimal, with base 2 instead of 10. Each place is worth a power of two:
Memory is organized in bytes of 8 bits. A byte is the smallest unit with its own address. Every multi-byte value (an int, a double, a pointer) occupies several consecutive addresses (§8).
2. Hexadecimal, and the sizes of things
2.1 Why hex?
Binary is long: the 16-bit number 15213 is 0011101101101101. Decimal is short but hides the bits: you cannot see from “15213” whether bit 5 is set. The fix is a base that is a power of two. Each digit then stands for a fixed group of bits, so conversion is mechanical and the bits stay visible.
- Octal (base 8): each digit = 3 bits. Historically used, still seen in Unix permissions (
chmod 755). - Hexadecimal (base 16): each digit = 4 bits, digits
0–9 A–F. Two hex digits = one byte. This is the programmer’s default, written with a0xprefix in C.
15213 = 0011 1011 0110 1101
= 3 B 6 D = 0x3B6D
0x1A2B = 1·16^3 + 10·16^2 + 2·16 + 11 = 6699
Skill to build: memorize the 16 nibbles (
0=0000 … 9=1001, A=1010, B=1011, C=1100, D=1101, E=1110, F=1111). Learn to write powers of two in hex quickly: 2n with n = 4k + j is a1,2,4or8(for j = 0..3) followed by k zeros. For example 219 = 24·4+3 =0x80000.
2.2 How big is each C type?
On every machine you will use in this course (x86-64 Linux, and also arm64 macOS/Linux), C uses the LP64 model:
| C type | bytes | typical use |
|---|---|---|
char | 1 | characters, raw bytes |
short | 2 | |
int | 4 | the “default” integer |
long | 8 | 64-bit integers; same width as a pointer |
pointer (T *) | 8 | addresses (64-bit virtual addresses) |
float / double | 4 / 8 | IEEE single / double precision |
C itself only promises minimum sizes. 64-bit Windows, for example, keeps long at 4 bytes (LLP64). When the exact width matters, use <stdint.h>: int8_t, uint32_t, int64_t… Every demo in this lecture does.
3. Bit-level manipulations
3.1 Boolean algebra, applied to every bit at once
George Boole (19th century) gave logic an algebra: encode true = 1, false = 0, and define
| op | name | result is 1 when |
|---|---|---|
A & B | AND | both are 1 |
A | B | OR | at least one is 1 |
~A | NOT | A is 0 |
A ^ B | XOR (exclusive or) | exactly one is 1 |
C applies these to every bit position independently, on any integer type. A byte is therefore 8 Boolean values processed in parallel. Run 01_bit_level_ops.c:
a = 0x69 = 0110_1001
b = 0x55 = 0101_0101
a & b = 0x41 = 0100_0001 (1 only where BOTH are 1)
a | b = 0x7d = 0111_1101 (1 where EITHER is 1)
a ^ b = 0x3c = 0011_1100 (1 where they DIFFER)
~a = 0x96 = 1001_0110 (every bit flipped)
Every law of Boolean algebra holds bit by bit. The demo checks De Morgan’s law ~(A & B) = ~A | ~B on all 65,536 pairs of bytes and finds 0 failures. XOR has extra properties worth knowing: x ^ x = 0, x ^ 0 = x, and it is its own inverse ((x ^ k) ^ k = x). These are the basis of simple checksums, RAID parity and “toggle a flag”.
3.2 Bit vectors are sets
A w-bit vector can represent any subset of {0, 1, …, w−1}: bit j is 1 exactly when j is in the set. The four operators then become the four set operations:
A = 0110_1001 = {0, 3, 5, 6}
B = 0101_0101 = {0, 2, 4, 6}
A & B intersection = {0, 6}
A | B union = {0, 2, 3, 4, 5, 6}
A ^ B symmetric difference = {2, 3, 4, 5}
~A complement = {1, 2, 4, 7}
This is not a toy. File permissions (rwxr-xr-x), CPU feature flags, the signal masks of Lecture 17 (sigset_t), the select file-descriptor sets of Lecture 21, and page-table entry flags (Lecture 12) are all bit vectors used as sets. A mask is a constant that selects bits. x & 0xFF keeps the low byte, x | 0x80 sets bit 7, and x & ~0x80 clears it.
3.3 Bitwise vs logical: & is not &&
C also has logical operators &&, ||, !. They look similar and behave very differently:
bitwise & | ~ | logical && || ! | |
|---|---|---|
| operates on | each bit | the whole value: 0 = false, non-zero = true |
| result | a full-width bit pattern | always exactly 0 or 1 |
| evaluates both sides? | always | short-circuits: stops as soon as the answer is known |
!0x41 = 0 !0x00 = 1 !!0x41 = 1
0x69 && 0x55 = 1 but 0x69 & 0x55 = 0x41
int *p = NULL; p && *p = 0 (right side never evaluated)
Short-circuiting is what makes p && *p safe: if p is NULL, *p is never evaluated. p & *p would dereference NULL. !!x is the idiom for “turn any non-zero value into exactly 1”.
There is also a precedence trap. In C, == binds tighter than &, so the even-test x & 1 == 0 parses as x & (1 == 0) = x & 0 = 0, for every x:
x = 4 (even). intended (x & 1) == 0 -> 1
written x & 1 == 0 parses as x & (1 == 0) -> 0
Always parenthesize bit tests. Compile with -Wall too: clang warns about both this trap and about && applied to constants. The first draft of the demo itself triggered the second warning (see the code README).
3.4 Shifts
- Left shift
x << k: move bits left by k, drop the bits that fall off the top, fill the bottom with 0s. - Right shift
x >> kcomes in two flavours, and choosing between them is the one place where shifting must know the type:- logical: fill the top with 0s (used for
unsignedtypes); - arithmetic: fill the top with copies of the sign bit (gcc and clang use it for signed types).
- logical: fill the top with 0s (used for
x = 0110_0011 x<<4 = 0011_0000 logical x>>4 = 0000_0110 arithmetic x>>4 = 0000_0110
x = 1001_0101 x<<4 = 0101_0000 logical x>>4 = 0000_1001 arithmetic x>>4 = 1111_1001
Why would anyone want the sign copied? Because then x >> k behaves like division by 2k for negative numbers too (almost; §7.4). The C standard leaves >> of negative values implementation-defined, but every compiler you will meet uses arithmetic shift for signed types.
Shift counts must be in [0, w). Shifting a 32-bit value by 32 or more, or by a negative amount, is undefined behavior. Demo 01 hides the count from the optimizer to see what the hardware does:
1u << 31 -> 0x80000000
1u << 32 -> 0x00000001
1u << 33 -> 0x00000002
Both x86-64 and arm64 use only the low 5 bits of the count for 32-bit shifts (k mod 32). So 1u << 32 gives 1, not the 0 that intuition suggests. C does not promise even that. make ubsan turns it into a run-time error (shift exponent 32 is too large for 32-bit type). This is the Lecture 1 lesson again: undefined behavior means the hardware’s answer and the compiler’s assumptions are both fair game.
4. Integers: unsigned and two’s complement
4.1 Intuition: a fixed number of points on a number line
With w bits there are exactly 2w patterns, so a w-bit integer type has exactly 2w points on its number line. Which numbers those points stand for is a choice. The slides show one 3-bit line labelled four different ways: 0..7, −4..3, fractions, even letters. Demo 02 prints the three integer choices that matter:
bits unsigned sign-magnitude two's complement
000 0 0 0
001 1 1 1
010 2 2 2
011 3 3 3
100 4 0 -4
101 5 -1 -3
110 6 -2 -2
111 7 -3 -1
4.2 Unsigned: the plain place-value reading
Add 1 to the largest value 111 and the true answer 1000 needs 4 bits. The top bit is lost and you get 000. This is overflow, and for unsigned numbers it simply means arithmetic modulo 2w: the number line is really a circle.
4.3 How to represent negative numbers? Attempt 1: sign-magnitude
The obvious idea is to use the top bit as a sign (0 = +, 1 = −) and the rest as the magnitude. It has two flaws:
- Two zeros:
000= +0 and100= −0, so equality testing needs a special case. - Ordinary addition gives wrong answers. 1 + (−1) =
001+101=110, which reads as −2. The hardware would need a separate, sign-aware adder.
Demo 02 measures how bad it is. Over every 3-bit pair whose true sum fits, it adds the patterns with an ordinary binary adder and decodes the result:
sign-magnitude : 23 of 52 in-range sums come out right
two's complement: 48 of 48 in-range sums come out right
4.4 Attempt 2: two’s complement, the trick
The slides derive two’s complement from three wishes: 1 should be 001; −1 + 1 should be 0; and ordinary addition (with the carry out of the top simply discarded) should just work. Then −1 must be the pattern that gives 000 when added to 001, and that is 111, because 111 + 001 = 1000 → 000. Likewise −2 = −1 − 1 = 110. Check: −2 + 5 = 110 + 101 = 1011 → 011 = 3 ✓.
Written as a formula, two’s complement is unsigned with one change: the top bit’s weight is negative.
For 3 bits the weights are −4, 2, 1, so 101 = −4 + 1 = −3. Consequences:
- every negative number starts with
1, so the top bit is a sign bit (but unlike sign-magnitude, the rest is not a magnitude); - there is exactly one zero;
- the range is asymmetric: −4 has no positive partner in 3 bits.
bits.h implements B2U and B2T straight from these sums. The demos use them to check that C’s casts agree with the definitions.
4.5 Negation: flip the bits and add one
To negate x: invert every bit, then add 1: −x = ~x + 1. Why? A number and its bitwise complement have no 1s in common, so their sum is all 1s: x + ~x = 11…1 = −1. Adding 1 to both sides gives x + (~x + 1) = 0, so ~x + 1 must be −x. Demo 02 checks all 16 four-bit values:
5 0101 1011 -5
-8 1000 1000 -8 <- -(-8) = +8 does not fit, so TMin stays TMin
correct for 15 of 16 values (all except TMin)
TMin is its own negation. That is the price of the asymmetric range, and a real source of bugs: abs(INT_MIN) is still negative.
4.6 Ranges, and the slide’s 15213 example
w UMax TMax TMin
8 255 127 -128
16 65535 32767 -32768
32 4294967295 2147483647 -2147483648
64 18446744073709551615 9223372036854775807 -9223372036854775808
15213 = 0x3b6d = 0011_1011_0110_1101
-15213 = 0xc493 = 1100_0100_1001_0011
Some patterns are worth knowing by sight. UMax = 11…1; TMax = 011…1; TMin = 100…0; −1 = 11…1 (the same bits as UMax). The identities |TMin| = TMax + 1 and UMax = 2·TMax + 1 follow directly from the weights. Note that 15213 and −15213 add to 0x10000, which truncates to 0x0000: the ordinary adder gives 0, as it should.
Does C guarantee two’s complement? Until C23 the standard allowed sign-magnitude and ones’ complement too. Every machine still in use is two’s complement, and C23 made it mandatory. These notes, like CS:APP, assume it everywhere.
5. Conversion and casting between signed and unsigned
5.1 A cast keeps the bits and changes the meaning
Casting between a signed and an unsigned type of the same width leaves the bit pattern unchanged and only reinterprets it. The value changes exactly when the sign bit is set:
4-bit view: -8 -> 1000 -> 8 (+16) ... -1 -> 1111 -> 15 (+16)
32-bit: (unsigned) -1 = 4294967295
(unsigned) -12345 = 4294954951
(int) 2147483648U = -2147483648
On the circle picture, the non-negative half of the signed line is shared by both types. The negative half of the signed line sits exactly where the upper half of the unsigned line sits, shifted by 2w.
5.2 Where C converts for you
- Constants are signed by default. A
Usuffix makes them unsigned (0U,4294967259U). Subtly, a decimal constant too big forintbecomes alongon LP64, while a hex constant becomesunsigned intif it fits (Exercise 2). - Explicit casts:
(int) ux,(unsigned) ty. - Implicit conversions happen on assignment (
tx = ux;), when passing arguments (fun(tx)wherefuntakesunsigned), and, most dangerously, inside expressions.
5.3 The rule that bites: mixed expressions become unsigned
If an expression mixes a signed and an unsigned operand of the same width, the signed one is converted to unsigned, including in the comparisons
<,>,==,<=,>=.
Demo 03 reproduces the slide’s table. Every relation is computed by C, and the “evaluated as” column is reported by the compiler itself through C11 _Generic:
constant 1 constant 2 rel evaluated as
0 0U == UNSIGNED
-1 0 < signed
-1 0U > UNSIGNED
2147483647 -2147483647 - 1 > signed
2147483647U -2147483647 - 1 < UNSIGNED
-1 -2 > signed
(unsigned)-1 -2 > UNSIGNED
2147483647 2147483648U < UNSIGNED
2147483647 (int)2147483648U > signed
Read the third row twice: −1 > 0U, because −1 becomes 4294967295. (Why write TMin as -2147483647 - 1? The literal 2147483648 is too big for an int; negating it would give a long, not an int.)
5.4 Three real bugs
Demo 03’s PART C:
(1) for (unsigned i = 2; i >= 0; i--) -- values of i: 2 1 0 4294967295 4294967294 ...
(2) strlen("ab") - strlen("abc") = 18446744073709551615, so (strlen(s)-strlen(t) > 0) is 1
(3) len = min(KSIZE=1024, maxlen=-1) = -1 passes the size check,
but memcpy's size_t parameter would receive 18446744073709551615 bytes
- An unsigned counter is always ≥ 0, so a count-down loop never ends.
strlenreturnssize_t, which is unsigned. A “negative” difference wraps to a huge positive number. Compare the lengths directly instead (strlen(s) > strlen(t)).- This one is a real security hole. It is the FreeBSD
getpeernamebug described in CS:APP §2.2.8. A kernel routine clamped a signed user-supplied length to the buffer size. A negative length passed the clamp and was then handed tomemcpyas an enormoussize_t, which would copy kernel memory out to the user. The demo only computes the length that would have reachedmemcpy. The fix was to declare lengths assize_tfrom the start.
5.5 When should you use unsigned?
CS:APP’s advice is sensible. Don’t use unsigned just because a quantity can’t be negative: mixing it with signed values breeds the bugs above. That is one reason Java has no unsigned integers. Do use unsigned when you need modular arithmetic (hashes, checksums, multiprecision arithmetic), when the value is really a bit pattern (flags, masks, sets), or when an interface demands it (size_t). And keep -Wall -Wextra on: the compiler flags every mixed comparison in demo 03. The demo has to switch those warnings off with pragmas just to compile cleanly.
6. Expanding and truncating
6.1 Expanding keeps the value
To widen a w-bit value to w + k bits:
- unsigned → zero extension: add k zeros on top;
- signed → sign extension: add k copies of the sign bit.
uint8_t 1 = 0000_0001 -> uint16_t = 0000_0000_0000_0001 (zeros added)
int8_t -1 = 1111_1111 -> int16_t = 1111_1111_1111_1111 (sign bit copied)
5-bit -10 = 1_0110 -> 6-bit 11_0110 = -10
Why does copying the sign bit preserve the value? It is enough to show that adding one copy preserves it. Before, the top bit weighs −2w−1. After adding a new top bit, the new bit weighs −2w and the old top bit now weighs +2w−1. If the sign bit is 1, the total contribution is −2w + 2w−1 = −2w−1, unchanged. Repeat k times by induction. Demo 04 also checks C’s int8_t → int16_t conversion on all 256 values: 0 failures.
x86-64 has dedicated instructions for both kinds: movzbl/movzwl zero-extend, and movsbl/movswl/movslq sign-extend. You will see them constantly in Lecture 3.
6.2 Truncating drops the high bits, and may change the value
Narrowing simply discards the top bits:
uint16_t 1000 = 0000_0011_1110_1000 -> uint8_t 1110_1000 = 232 (1000 mod 256)
5-bit 10 = 0_1010 -> 4-bit 1010 = -6 SIGN CHANGED
5-bit -10 = 1_0110 -> 4-bit 0110 = 6 SIGN CHANGED
5-bit 2 = 0_0010 -> 4-bit 0010 = 2
int 53191 = 0x0000cfc7 -> short 0xcfc7 = -12345 (CS:APP's example)
For unsigned values truncation is exactly x mod 2^w. For signed values it is “mod, then reinterpret”, which can flip the sign. Small-magnitude values survive; large ones are mangled. Truncation is free in hardware, because a narrower register name such as %eax simply refers to the low part of a wider one such as %rax.
6.3 Changing size and signedness
When both change at once, C converts the size first, then the signedness:
short s = -12345 = 0xcfc7
(unsigned) s = 4294954951 = 0xffffcfc7 (sign-extended first)
(unsigned)(unsigned short) s = 53191 = 0x0000cfc7 (zero-extended)
7. Arithmetic
7.1 Addition: one adder for both kinds of number
Adding two w-bit numbers can produce a w+1-bit true sum. The hardware keeps the low w bits and discards the carry, so unsigned addition is
Two’s-complement addition does exactly the same thing to the bits:
bits 0xe9 + 0xd5: true sum 0x1be (9 bits) -> keep 8 bits: 0xbe
as unsigned: 233 + 213 = 446, mod 256 = 190
as signed : -23 + -43 = -66 (bits 0xbe)
all 65536 byte pairs: UAdd bits != TAdd bits in 0 cases
This is the payoff of two’s complement. The CPU needs one adder, and in C (int)((unsigned)u + (unsigned)v) gives the same result as u + v (if u + v doesn’t overflow; overflowing it is undefined).
7.2 Overflow: when and how to detect it
The unsigned sum overflows when the true sum ≥ 2w. It then wraps once (subtract 2w). The detection test is s = u + v; overflow ⇔ s < u.
The two’s-complement sum can overflow in two directions:
- positive overflow: true sum ≥ 2w−1 → the result comes out negative;
- negative overflow: true sum < −2w−1 → the result comes out non-negative.
Demo 05 draws the whole 4-bit table (+ positive overflow, - negative overflow, . exact):
u= -8 - - - - - - - - . . . . . . . .
...
u= 7 . . . . . . . . . + + + + + + +
positive overflows: 28, negative overflows: 36, exact: 192 of 256
rule 'same-sign operands, different-sign result' misclassified 0 cases
The overflow regions are two triangles in the corners, mirroring the slide’s 3-D plot. The negative triangle is larger (36 vs 28) because the range [−8, 7] has one more negative value. The detection rule is: overflow happened if and only if both operands have the same sign and the result has the other sign. Adding two numbers of opposite signs can never overflow. The demo confirms the rule on all 256 pairs. In Lectures 3–4 you will see that the CPU computes exactly these two tests in hardware: the carry flag CF (unsigned overflow) and the overflow flag OF (signed overflow).
7.3 Multiplication: keep the low w bits
The exact product of two w-bit numbers can need 2w bits. C, like the hardware, keeps only the low w bits. Again the low bits are the same for signed and unsigned operands:
unsigned 255 * 2 = 510 -> low 8 bits 254
signed -1 * 2 = -2 -> low 8 bits 0xfe
all 65536 byte pairs: unsigned vs signed product bits differ in 0 cases
(Only the upper half of a full 2w-bit product depends on signedness. That is why x86-64 has separate mul and imul instructions for the full-width product.) Software that needs exact results uses arbitrary-precision libraries such as GMP, or Python’s built-in integers.
7.4 Shifts as multiplication and division
Multiplying by 2k is a left shift. u << k = u · 2^k for signed and unsigned values alike, with the same low-bit truncation as *. Since shifts and adds are cheaper than a general multiply, compilers rewrite multiplication by constants: x · 24 = (x ≪ 5) − (x ≪ 3), or (x · 3) ≪ 3.
Dividing by 2k is a right shift, almost. For unsigned values a logical right shift gives exactly ⌊u / 2k⌋. For signed values the arithmetic shift rounds toward −∞, but C’s integer division / rounds toward zero. The two disagree for negative numbers that are not exact multiples:
x k x>>k x/2^k (C) biased shift
5 1 2 2 2
-5 1 -3 -2 -2
-15213 4 -951 -950 -950
The fix is to add a bias of 2k − 1 to negative values before shifting:
The bias pushes every negative value that isn’t already a multiple of 2k just far enough that the floor becomes the ceiling. Demo 05 checks all 16-bit x and k = 0..14 (983,040 cases). The plain shift disagrees with C’s / in 425,986 cases; the biased shift disagrees in 0.
7.5 The compiler does it for you (preview of Lecture 3)
make asm shows the compiler applying §7.4 to times24, div8 and udiv8:
x86-64 times24: shlq $3,%rdi ; leaq (%rdi,%rdi,2),%rax # (x<<3)*3, no imul
x86-64 div8: leaq 7(%rdi),%rax ; testq %rdi,%rdi ; cmovnsq %rdi,%rax ; sarq $3,%rax
x86-64 udiv8: movq %rdi,%rax ; shrq $3,%rax
arm64 div8: add x8,x0,#7 ; cmp x0,#0 ; csel x8,x8,x0,lt ; asr x0,x8,#3
Read div8 slowly. It computes x + 7 (the bias for k = 3) and tests the sign of x. If x is non-negative it keeps the unbiased x (cmovns = “conditional move if not sign”). Then it shifts arithmetically by 3. That is exactly the formula from §7.4, written by the compiler itself, and arm64 does the same with csel. udiv8 needs no bias, because unsigned division is a logical shift. You will learn every one of these instructions in Lectures 3–4.
8. Byte ordering
8.1 Two conventions
A 4-byte int occupies addresses a, a+1, a+2, a+3. Which byte of the value goes where?
- Big endian: the most significant byte at the lowest address (as you’d write it). Used by IBM mainframes, SPARC, old PowerPC Macs, and the Internet’s protocols.
- Little endian: the least significant byte at the lowest address. Used by x86-64, and by ARM as configured by Android, iOS, macOS and Linux.
x = 0x01234567 stored at &x
bytes at &x, &x+1, &x+2, &x+3: 67 45 23 01
this machine is LITTLE endian
a big-endian machine would store: 01 23 45 67
The names come from Gulliver’s Travels, where a war is fought over which end of a boiled egg to break. Like that war, neither choice is better. Bits within a byte are not reversed, and single bytes and strings are unaffected ("12345" is 31 32 33 34 35 00 everywhere).
8.2 When does it matter?
Never, while a program only works with its own values through their declared types. It matters the moment bytes cross a boundary:
- networks: protocols define network byte order = big endian, so a little-endian host converts with
htonl/ntohl(htonl(0x01234567)→01 23 45 67). You will meet these again in Lectures 19–20; - files written on one machine and read on another;
- reading memory dumps in a debugger (Lectures 3–6, bomblab);
- reading machine code. In the listing
81 c3 ab 12 00 00 add $0x12ab,%ebx, the 4-byte immediate is stored little endian:ab 12 00 00→0x000012ab.
8.3 Seeing it: show_bytes
CS:APP’s show_bytes casts the address of any object to unsigned char * and prints its bytes in address order. It is in bits.h. Demo 06 reproduces CS:APP Figure 2.6:
int 15213 : 6d 3b 00 00
int -15213 : 93 c4 ff ff
float 15213.0 : 00 b4 6d 46
int * &ival : 88 25 77 6f 01 00 00 00 (varies run to run: ASLR)
The int and the float hold “the same number” in completely different bit patterns. The pointer is 8 bytes, and its value changes every run because the OS randomizes where the stack lives (ASLR, Lecture 6).
9. Supplement: the fields of an IEEE floating-point number
The Fall 2026 lectures skip CS:APP §2.4. Lecture 1’s “floats are not reals” and datalab’s traditional float puzzles still assume you know how a float is laid out, so here is the minimum. A 32-bit float has three unsigned fields:
s | exponent (8 bits) | fraction (23 bits)
and three classes, decided by the exponent field e:
| class | condition | value |
|---|---|---|
| normalized | 0 < e < 255 | (−1)s × 1.f × 2e − 127 |
| denormalized | e = 0 | (−1)s × 0.f × 21 − 127 |
| special | e = 255 | f = 0: ±∞; f ≠ 0: NaN |
The bias 127 lets an unsigned field store both positive and negative exponents. The implied leading 1 of normalized numbers buys one free bit of precision, giving 24 significant bits. Denormals fill the gap near 0 evenly (“gradual underflow”) and give 0 itself, with a separate −0. 07_float_fields.c decodes several values and rebuilds each one from the formula:
15213.0 0 | 1000_1100 | 110_1101_1011_0100_0000_0000 normalized E= 13 rebuilt=15213 ok
0.1 0 | 0111_1011 | 100_1100_1100_1100_1100_1101 normalized E= -4 rebuilt=0.100000001 ok
1.4e-45 0 | 0000_0000 | 000_0000_0000_0000_0000_0001 denormalized E=-126 rebuilt=1.40129846e-45 ok
+inf 0 | 1111_1111 | 000_0000_0000_0000_0000_0000 infinity E= 128 rebuilt=inf ok
0.1f is really 0.10000000149011611938
16777216.0f + 1.0f = 16777216.0 (a float holds 24 significant bits)
Compare 15213.0’s fraction bits with 15213’s integer bits from §4.6, 11_1011_0110_1101. Drop the leading 1, which becomes the implied bit, and the rest appears at the start of the fraction field. Converting an int to a float literally moves the bits. The 0.1 row shows its repeating 1100 pattern, rounded up in the last place, which is why 0.1 is inexact. A double is the same design with 1 + 11 + 52 bits and a bias of 1023.
Summary
- Computers use bits because two states are robust against noise. Groups of bits encode numbers, text, instructions and anything else countable, and context decides which. Programmers write bits in hex, 4 bits per digit.
& | ^ ~act on every bit in parallel. On bit vectors they are the set operations.&& || !see only zero/non-zero, return 0 or 1, and short-circuit. Shifts come in logical and arithmetic flavours, and counts ≥ the width are undefined.- Unsigned = plain place values, arithmetic mod 2w. Two’s complement = the same, except the top bit’s weight is negative. That one change lets a single adder serve both kinds of number, gives one zero, and makes −x =
~x + 1. The range is asymmetric, so −TMin = TMin. - Casts between signed and unsigned keep the bits and change the value by ±2w. In mixed expressions the signed operand becomes unsigned, so −1 > 0U. Most real bugs come from
size_t. - Widening keeps the value (zero or sign extension). Narrowing keeps the low bits (mod 2w) and can flip the sign. C changes the size before the signedness.
- + and * produce identical bits for signed and unsigned values. Signed overflow happens exactly when two same-sign operands produce a different-sign result.
<< kmultiplies by 2k.>> kdivides but rounds toward −∞, so signed division needs the bias 2k − 1, and the compiler emits that sequence itself. - x86-64 and arm64 are little endian. Byte order matters only when bytes cross a boundary: network, file, dump, listing.
Common pitfalls
if (x & MASK == 0): precedence makes itx & (MASK == 0). Parenthesize bit tests.&&where you meant&(or||for|).-Wallcatches the constant cases, not all of them.- Shifting by ≥ the width, or by a negative amount, and shifting negative signed values left. All are undefined.
- Loop counters and lengths declared
unsigned/size_tcombined with>= 0tests or subtraction. - Comparing
intwithsizeof(...)orstrlen(...): theintsilently becomes unsigned. abs(INT_MIN),-INT_MIN,INT_MIN / -1: TMin has no positive counterpart (and on x86-64 the last one traps, see Lecture 1).- Assuming
x >> k == x / (1 << k)for negativex. - Writing a binary file on one machine and reading it on another, or sending raw
ints over a socket withouthtonl.
Exercises
-
Conversions. Write 0x3B6D in decimal and binary; write 219 and 232 − 1 in hex; and write −1 as a 16-bit hex pattern.
Answer
0x3B6D = 3·4096 + 11·256 + 6·16 + 13 = 15213 = 0011_1011_0110_1101. 219 = 24·4+3 = 0x80000. 232 − 1 = 0xFFFFFFFF. −1 in 16 bits = 0xFFFF. -
Predict the comparison on an LP64 machine (x86-64 Linux or arm64 macOS): (a)
-1 < sizeof(int); (b)-2147483648 < 2147483647; (c) the type of the literal0x80000000.Answer
(a) **0 (false)**. `sizeof` has type `size_t` (unsigned long), so −1 becomes 264 − 1. (b) **1 (true)**. The decimal literal `2147483648` doesn't fit in `int`, so it has type `long`, and negating it gives a `long` −2147483648. The comparison is done in signed `long` arithmetic. (c) **unsigned int**. A hexadecimal constant that doesn't fit in `int` takes the first of `unsigned int`, `long`, … that fits. Checked on the author's machine with `_Generic`. -
Lowest set bit. For an
int x, what doesx & -xcompute? Use −x =~x + 1to explain why. What is it forx = 12?Answer
It isolates the lowest 1-bit of *x*. Write *x* = (high bits) 1 0…0, with *k* trailing zeros. `~x` = (inverted high bits) 0 1…1; adding 1 carries through the *k* ones and gives (inverted high bits) 1 0…0. ANDing with *x* clears all high bits (they are inverted) and keeps the single 1 at position *k*. For 12 = 1100₂ the result is 4 = 100₂. For x = 0 the result is 0. -
Prove sign extension once more, for 2 copies. Show that the 4-bit pattern 1011 (= −5) and its 6-bit sign extension 111011 have the same value, using the weights.
Answer
4 bits: −8 + 0 + 2 + 1 = −5. 6 bits, weights −32 16 8 4 2 1: −32 + 16 + 8 + 0 + 2 + 1 = −5. The two new top bits contribute −32 + 16 = −16, and the old sign bit changed from −8 to +8 (a change of +16), so the total is unchanged. -
Unsigned overflow test. Prove that for w-bit unsigned u, v, the sum
s = u + voverflowed if and only ifs < u.Answer
If there was no overflow, *s* = *u* + *v* ≥ *u*. If there was, *s* = *u* + *v* − 2w, and since *v* < 2w, *s* = *u* − (2w − *v*) < *u*. So `s < u` exactly when the sum overflowed. (Testing `s < v` works equally well.) -
Find the bug (CS:APP practice problem 2.25). What happens when
length = 0, and how do you fix it?float sum_elements(float a[], unsigned length) { float result = 0; for (int i = 0; i <= length - 1; i++) result += a[i]; return result; }Answer
`length - 1` with `length = 0` is the unsigned value UMax. The comparison `i <= length - 1` converts `i` to unsigned, so it is always true: the loop reads far past the array and eventually segfaults. Fix: `i < length` (or declare `length` as `int`/`size_t` and use `<`). -
Endianness. Bytes at addresses 0x100–0x103 are
78 56 34 12. What 4-byte unsigned value is stored there on a little-endian machine? On a big-endian one?Answer
Little endian: least significant byte first → 0x12345678. Big endian: 0x78563412. -
Bias by hand. Compute −15213 / 16 with C’s rule, then with
>> 4alone, then with the bias.Answer
True quotient −950.8125. C rounds toward zero: −950. `>> 4` rounds toward −∞: −951. With the bias: (−15213 + 15) >> 4 = −15198 >> 4 = −950 (−15198 / 16 = −949.875, floor −950). This matches demo 05's row for *k* = 4.
The related lab: L1 (datalab)
Datalab asks you to implement small integer and floating-point functions under tight restrictions. You get only straight-line code (no loops or ifs), a small set of operators (typically ! ~ & ^ | + << >>), small constants, and a per-function operator budget. The float puzzles operate on the bits of a float through an unsigned integer. It is a lab about reasoning with exactly the tools of this lecture: masks, the two’s-complement identities, sign extension via arithmetic shift, overflow rules, and (for the float puzzles) the field layout of §9. These notes do not solve any datalab puzzle. The exercises above rehearse the reasoning instead. Recitation 1 introduces the lab’s tooling (dlc checks the operator rules, btest tests correctness).
Further reading
- CS:APP3e §2.1–2.3 and the practice problems at the end of each section. They are the closest thing to exam problems, and the book includes solutions.
- CS:APP3e §2.4 (floating point) for the full story behind §9: rounding modes, float arithmetic, and the casts between
int,floatanddouble. - The slide deck links an interactive bit-twiddling tutorial (
wiredream.com/learning-to-bit-twiddle). - Hacker’s Delight (H. S. Warren Jr.) for a catalogue of bit tricks. It is advanced, and a good companion after datalab.
Preview of Lecture 3: Machine-level programming I, basics
Now that you know what the bits mean, Lecture 3 shows what the CPU does with them. We meet x86-64’s 16 general-purpose registers (and why %eax is the low half of %rax), operands and the mov family (including the movz/movs extensions from §6), the general addressing mode D(Rb,Ri,S), and lea, the address-computing instruction that compilers abuse for arithmetic like the times24 you saw in §7.5. We also meet the arithmetic and logical instructions that implement §3 and §7, the condition codes that record carry and overflow, and the path from C to assembly to machine code. Bring Lecture 2’s view of a register: a fixed-width bit pattern whose meaning depends on the instruction that reads it.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| bit / byte / word | 位(比特)/ 字节 / 字 |
| binary / decimal / hexadecimal / octal | 二进制 / 十进制 / 十六进制 / 八进制 |
| nibble | 半字节(4 位) |
| analog / digital | 模拟 / 数字 |
| most / least significant bit (MSB / LSB) | 最高 / 最低 有效位 |
| Boolean algebra | 布尔代数 |
| AND / OR / NOT / XOR | 与 / 或 / 非 / 异或 |
| bitwise operator / logical operator | 按位运算符 / 逻辑运算符 |
| short-circuit evaluation | 短路求值 |
| operator precedence | 运算符优先级 |
| bit vector / mask | 位向量 / 掩码 |
| set intersection / union / complement / symmetric difference | 交集 / 并集 / 补集 / 对称差 |
| left shift / logical right shift / arithmetic right shift | 左移 / 逻辑右移 / 算术右移 |
| unsigned encoding | 无符号编码 |
| sign-magnitude | 原码(符号-数值表示) |
| ones’ complement / two’s complement | 反码 / 补码 |
| sign bit | 符号位 |
| weight (of a bit) | 位权 |
| UMax / TMax / TMin | 无符号最大值 / 有符号最大值 / 有符号最小值 |
| cast / implicit conversion | 强制类型转换 / 隐式类型转换 |
| usual arithmetic conversions | 常规算术转换 |
| zero extension / sign extension | 零扩展 / 符号扩展 |
| truncation | 截断 |
| overflow (positive / negative) | 溢出(正溢出 / 负溢出) |
| modular arithmetic | 模运算 |
| carry / carry flag / overflow flag | 进位 / 进位标志 / 溢出标志 |
| rounding toward zero / toward −∞ | 向零舍入 / 向负无穷舍入 |
| bias | 偏置(偏移量) |
| byte ordering / endianness | 字节顺序 / 字节序(端序) |
| big endian / little endian | 大端 / 小端 |
| network byte order | 网络字节序 |
| disassembly | 反汇编 |
| IEEE 754 floating point | IEEE 754 浮点数 |
| exponent / fraction (significand) / bias | 阶码 / 尾数 / 偏置值 |
| normalized / denormalized | 规格化 / 非规格化 |
| infinity / NaN (not a number) | 无穷大 / 非数 |
| undefined behavior | 未定义行为 |
| implementation-defined behavior | 实现定义行为 |