Chapter 04 / 15 · Webster International
Computer Science: Bits to Algorithms
Binary and hexadecimal arithmetic, bytes and encodings, memory, logic, complexity, data structures and concurrency.
Every higher-level service ultimately relies on representation: numbers, addresses, memory, algorithms and well-defined transitions.
01 / FIELD NOTE
A bit, a byte and positional number systems
Mental model: a numeral is a sequence of digits multiplied by powers of its base, not a different underlying quantity. In base 2, 101010 = 1×32+1×8+1×2 = 42; in base 16, 2A = 2×16+10 = 42. Eight bits form one byte; each hex digit encodes four bits. Prefixes 0b and 0x are notation, not bytes on the wire. Work from right to left to diagnose an unexpected value.
Binary and hex appear in protocol flags, image bytes, RGB colours, diagnostics and permissions. Exact conversion prevents misleading logs and accidental type coercion.
Example A — a device sends 0x2A: inspect the two nibbles (0010 1010) to verify decimal 42. Example B — a CSS colour component 0xFF means 255, not decimal 0. A packet parser must also know byte order, which base conversion alone does not reveal.
// Runnable: node or modern browser console
for (const n of [42n, 255n]) {
console.log(n.toString(2).padStart(8, '0'), n.toString(16).toUpperCase());
}
// 00101010 2A; 11111111 FFHands-on exercise · reveal the verification check
Convert 173 to eight-bit binary and hex by hand, then check using BigInt(173).toString(2) and .toString(16). What changes when padded to 16 bits?
173 = 10101101₂ = AD₁₆. Sixteen-bit display is 0000000010101101; the numeric value is unchanged.
02 / FIELD NOTE
Count, convert and mask in binary
Mental model: each bit position can represent one independent on/off flag. OR (|) combines flags, AND (&) tests membership, AND with complement (~) clears a flag, and XOR (^) toggles it. JavaScript Number bitwise operators coerce to signed 32-bit integers; BigInt bitwise operators avoid that width limit, but a protocol still defines its own fixed width.
Compact flags are useful for device control and feature negotiation; understanding the masks also makes debugging packed permission values possible.
Example A — a broadcast controller reports READ|WRITE as 0b011; testing EXEC must return false. Example B — a feature toggle can remove WRITE without disturbing READ. Security authorization must still be checked server-side against trusted identity, not a client-supplied mask.
// Runnable: node or modern browser console
const READ=1n, WRITE=2n, EXEC=4n;
let flags=READ|WRITE;
console.log((flags&WRITE)!==0n, (flags&EXEC)!==0n); // true false
flags &= ~WRITE;
console.log(flags===READ); // trueHands-on exercise · reveal the verification check
Start with READ|EXEC. Add WRITE, then clear EXEC. Print the final mask in binary and verify WRITE is enabled.
Final mask is 0b011 (3), READ and WRITE true, EXEC false; using BigInt gives the same logical result.
03 / FIELD NOTE
Signed integers, overflow and floating point
Mental model: n-bit two's-complement integers interpret the high bit as negative; unsigned 11111111₂ is 255 but signed 8-bit is -1. JavaScript Number uses binary64 floating point: many decimals are approximations, and integers beyond 2^53-1 lose exactness. Choose a representation based on domain invariants, not visual formatting.
An incorrect integer range or rounding rule can silently corrupt invoice totals, timestamps, counters or inventory.
Example A — a signed device register containing FF decodes to -1, not 255. Example B — store CAD 12.35 as 1235 integer cents for addition; for tax/FX rules, use a defined decimal precision and explicit rounding policy rather than naive floating-point equality.
// Runnable: node or modern browser console
console.log(BigInt.asIntN(8, 255n).toString()); // -1
console.log((1235+265)/100); // 15
console.log(0.1+0.2===0.3); // false
console.log(Number.MAX_SAFE_INTEGER+1===Number.MAX_SAFE_INTEGER+2); // trueHands-on exercise · reveal the verification check
Add CAD 12.35 and CAD 2.65 using integer cents; decode signed 8-bit 0x80. Compare with 0.1+0.2.
1235+265=1500 cents ($15.00); 0x80 as signed 8-bit is -128; 0.1+0.2 is not exactly 0.3 in binary64.
04 / FIELD NOTE
Text, Unicode and UTF-8
Mental model: Unicode code points identify abstract characters, UTF-8 serializes them to 1–4 bytes, JavaScript strings use UTF-16 code units, and grapheme clusters approximate user-perceived characters. These are different lengths. Normalize only for an explicitly chosen matching policy; display original spelling and do not split grapheme clusters when truncating.
Names, search, database limits and accessible character counters must work for multilingual text, combining accents and emoji.
Example A — e followed by combining acute accent is two code points but one grapheme. Example B — an emoji sequence can be multiple code points and many UTF-8 bytes yet appear as one symbol; a UI limit should specify whether it counts bytes, code points or graphemes.
// Runnable: node or modern browser console with Intl.Segmenter
const s='e\u0301';
const count=[...new Intl.Segmenter('en',{granularity:'grapheme'}).segment(s)].length;
console.log(s.length, [...s].length, count, new TextEncoder().encode(s).length);
// 2 2 1 3Hands-on exercise · reveal the verification check
Measure the UTF-16 units, code points, graphemes and UTF-8 bytes of 'A' and 'e\u0301'. Normalize the latter with NFC and measure again.
'A' is 1/1/1/1. Decomposed accent is 2/2/1/3; NFC yields 1 UTF-16 unit, 1 code point, 1 grapheme, 2 UTF-8 bytes.
05 / FIELD NOTE
Memory, stack, heap and references
Mental model: function calls consume stack frames; dynamically allocated objects have lifetimes determined by reachable references and the runtime's memory management. A Map or event listener can keep an otherwise unused object alive. Resident memory, heap used and garbage collection are different signals; measure trends across repeated workloads.
A leak may only appear after thousands of CRM navigations or feed refreshes, causing latency, crashes and costly restarts.
Example A — an event handler retains a detached DOM panel until the listener is removed. Example B — a process-wide cache of every searched artist grows without a bound; impose an explicit size limit or TTL and measure hit rate and memory.
// Runnable: node or modern browser console; bounded FIFO cache
const cache=new Map();
function put(key,value){
if(cache.has(key)) cache.delete(key);
cache.set(key,value);
if(cache.size>2) cache.delete(cache.keys().next().value);
}
put('a',1);put('b',2);put('c',3);
console.log([...cache.keys()]); // ['b','c']Hands-on exercise · reveal the verification check
Run ten thousand distinct cache writes with max size 2; compare to a naive Map that never evicts. Explain why RSS may not fall immediately.
Bounded cache.size remains 2; naive Map.size reaches 10000. Garbage collectors may retain reserved memory even after objects are freed.
06 / FIELD NOTE
Algorithms, data structures and Big O
Mental model: Big O expresses growth as input size increases, not exact runtime. A nested search over n records may be O(n²), while building a Set of identifiers and making average fast lookups is typically O(n) time with O(n) extra memory. Database indexes change query costs but add write/storage overhead.
The same event deduplication algorithm can feel instantaneous for 20 records and time out for millions.
Example A — deduplicate 100,000 concert events by stable source ID with a Set. Example B — use a Map for venue lookup rather than repeatedly scanning a 5,000-venue array; benchmark realistic data before changing code.
// Runnable: node or modern browser console
const records=[{id:'a'},{id:'b'},{id:'a'}];
const seen=new Set();
const unique=records.filter(row=>{
if(seen.has(row.id)) return false;
seen.add(row.id);return true;
});
console.log(unique.map(x=>x.id)); // ['a','b']Hands-on exercise · reveal the verification check
Implement deduplication by ID using a nested scan and using a Set. Estimate comparisons for 10,000 unique records.
Nested scan approaches 49,995,000 pair comparisons; Set approach makes about 10,000 membership checks, plus inserts, with additional memory.
07 / FIELD NOTE
Boolean logic and state machines
Mental model: a workflow is a finite set of states plus an explicit transition relation. Guards check whether a transition is permitted; side effects occur only after a validated, durable transition. One status field avoids contradictory boolean combinations such as paid=true and voided=true.
Bookings, invoices and moderation workflows need predictable behaviour across UI, API and background jobs.
Example A — invoice draft→issued→paid; voiding a paid invoice requires a separate refund flow. Example B — a dog-walk visit confirmed→in_progress→completed, while cancellation is allowed only before completion. Display state and errors in text, not colour alone.
// Runnable: node or modern browser console
const allowed={draft:['issued','voided'],issued:['paid','voided'],paid:[],voided:[]};
function transition(from,to){
if(!allowed[from]?.includes(to)) throw Error('Invalid transition');
return to;
}
console.log(transition('draft','issued')); // issued
try{transition('voided','paid')}catch(e){console.log(e.message)} // Invalid transitionHands-on exercise · reveal the verification check
Add a refunded state reached only from paid, then try voided→refunded. Identify where an audit event belongs.
paid→refunded succeeds; voided→refunded fails; the audit event is committed with the durable transition, not before it.
08 / FIELD NOTE
Processes, threads, async I/O and race conditions
Mental model: processes isolate address spaces, threads can share memory, and async I/O interleaves tasks while waiting. Concurrent operations can observe the same old state even in a single-threaded event loop. Correctness comes from atomicity and ordering at the shared resource, not from a JavaScript runtime assumption.
Two simultaneous checkout or booking requests must not both reserve the last unit of stock or the same time slot.
Example A — two async read-modify-write calls both see 0 and each write 1: a lost update. Example B — in PostgreSQL, UPDATE inventory SET stock=stock-1 WHERE sku=$1 AND stock>0 RETURNING stock; succeeds for only one buyer when stock starts at 1; handle zero returned rows as sold out.
// Runnable: node or modern browser console; demonstrates lost update
let count=0;
async function unsafe(){const before=count;await Promise.resolve();count=before+1;}
Promise.all([unsafe(),unsafe()]).then(()=>console.log(count)); // 1, not 2Hands-on exercise · reveal the verification check
Run the race ten times, then replace it with a serialized queue or transactional database update. For one stock unit, simulate two buyers.
Unsafe demo ends at 1 despite two calls. Serialized increment ends at 2; conditional stock reservation permits exactly one success and stock never drops below zero.
Base conversions with worked arithmetic
Binary uses place values 1,2,4,8 and hexadecimal groups binary into nibbles of four. Decimal 173 equals binary 10101101 and hexadecimal AD: 10×16+13=173. Repeated division finds digits; multiply-and-add reverses the operation.
Hex is a compact human-readable representation of bytes used in memory dumps, URLs, hashes and colours.
Mask 173 with 0x0F to inspect the low nibble D; shift right four bits to inspect high nibble A.
Hands-on exercise · reveal the verification check
Convert 2026 to binary and hex by hand, then verify with the converter.
Your calculation reconstructs exactly 2026 when converted back.
Bit shifts, masks and two's complement
Left shift multiplies an unsigned bit pattern by powers of two until capacity is exceeded; right shift may preserve a sign bit depending on operator and language. Two's complement stores negative values by flipping bits and adding one within a fixed width.
Permissions, network fields and packed flags depend on width, signedness and exact operator behaviour.
For 8-bit -5: +5 is 00000101; flip to 11111010, add one to get 11111011. Mask the low four bits to recover 1011 (0xB) and compare signed/unsigned interpretations of the same byte.
Hands-on exercise · reveal the verification check
Encode read=1, write=2, admin=4 and evaluate every combination.
Check no bit mask unintentionally grants admin.
Floating point error and numerical decisions
IEEE-style binary floating point cannot represent many decimal fractions exactly; arithmetic can accumulate roundoff. Decide acceptable tolerance, use decimal types or integer minor units for money, and define rounding policy explicitly.
A seemingly tiny error in invoicing can compound across fees, taxes and refunds.
For an $18.75 price and 13% tax, calculate in integer cents/decimal, decide rounding at the line or invoice boundary and test both.
Hands-on exercise · reveal the verification check
Write test cases for 0.1+0.2 and 1000 sequential 1-cent additions.
Integer/decimal ledger matches the intended cents exactly.
Algorithms and amortized complexity
Asymptotic notation separates growth from hardware speed. Dynamic arrays offer amortized constant-time append, while inserting at the front can shift all elements; sorting is often O(n log n). Measure realistic distributions, not just best cases.
The data structure that works for 20 records may collapse at a million records.
Compare linear lookup of a million artist IDs to a Map keyed by ID; benchmark with warmup and representative sizes.
Hands-on exercise · reveal the verification check
Implement duplicate checking with array.includes and with Set.
Record time and memory for 100, 10k and 100k values.
Unicode normalisation and grapheme clusters
Visible text, code points, UTF-16 units and UTF-8 bytes are different measurements. Unicode normalisation can make canonically equivalent sequences comparable; grapheme segmentation supports user-visible cursor and length semantics.
Name search and truncation can misbehave for combining marks, accents and emoji.
Compare Café written with composed é versus e + combining acute; normalize for matching while preserving original display spelling.
Hands-on exercise · reveal the verification check
Test names in multiple scripts plus emoji and accents.
No code-point slicing corrupts a displayed grapheme.
Concurrency, ordering and the lost update
Two async requests can overlap across awaits even on a single JavaScript thread. Read-modify-write without an atomic database operation can lose updates; locks or version comparisons enforce an invariant.
Concurrent writes are common in checkouts, bookings, collaborative edits and sync.
Two users both see one available ticket; update WHERE remaining > 0 and check affected-row count in a transaction.
Hands-on exercise · reveal the verification check
Simulate two simultaneous reservations for one item.
Exactly one reservation succeeds and inventory never becomes negative.
Numbers and machine representation
Two's complement and bitwise flags in real protocols
Unsigned binary encodes nonnegative magnitudes; two's complement typically encodes signed fixed-width integers by wrapping arithmetic modulo a power of two. Bitwise AND, OR, XOR and shifts operate on bit positions; width and signedness change the interpretation.
Device drivers, binary protocols, permissions and compact flags all rely on accurate bit reasoning.
For an 8-bit value, show how 255 becomes -1 when interpreted as signed, and use a mask to extract a capability flag.
Hands-on exercise · reveal the verification check
Write binary 11111111 and interpret it as signed and unsigned 8-bit.
Explain why the two interpretations differ.
Floating-point representation, rounding and money
IEEE 754 binary floating-point stores sign, exponent and significand and cannot exactly represent many decimal fractions. Equality with a fixed epsilon can be wrong across magnitude ranges; use decimal or integer minor units for money and explicit rounding rules.
Financial and booking calculations can drift subtly when values pass across languages and databases.
Represent a $12.35 price as 1235 cents, or use an appropriate decimal type for currencies requiring fractional minor units.
Hands-on exercise · reveal the verification check
Compute 0.1 + 0.2 and inspect the result.
Choose a representation for a payment ledger and justify it.
Unicode grapheme clusters, normalization and text searching
Unicode code points are not necessarily user-perceived characters; combining marks and emoji sequences can occupy multiple code points or UTF-16 code units. Normalization matters for comparison and searching, while case folding is locale-sensitive. Store and display text without assuming one code unit is one letter.
String length, text truncation and name search fail in surprising ways when international text is treated as ASCII.
Test a search box with accented names, Lithuanian characters and emoji, comparing NFC and NFD representations.
Hands-on exercise · reveal the verification check
Compare two canonically equivalent strings with different code point sequences.
Verify normalized search finds both forms.
Hash tables, trees, graphs and complexity trade-offs
Arrays favor indexed iteration, maps favor key lookup, balanced trees support ordered ranges and graphs encode relationships. Big-O describes growth, not a complete runtime prediction; cache locality, memory allocations, dataset size and IO patterns also affect performance.
Choosing data structures sensibly often removes an entire class of optimization problems.
Use a map for event IDs, a sorted index for date ranges and graph traversal for a network of artists and collaborators.
Hands-on exercise · reveal the verification check
Compare lookup times for an array scan and a map using 100k IDs.
Explain measurement variance and asymptotic expectations.
Race conditions, locks and deadlock prevention
Concurrency allows interleaving; simultaneous writes may violate invariants without locks, transactions or atomic operations. Locks protect critical sections but can deadlock when acquired inconsistently. Messages and immutable data reduce shared mutable state, though ordering remains important.
A calendar can double-book when two requests each read an available slot before either commits.
Model two clients racing to reserve the last appointment; protect the constraint with an atomic database operation.
Hands-on exercise · reveal the verification check
Write a test that races two reservations for one slot.
Exactly one succeeds and the database contains one booking.