Lawfare Group → Knowledge Institute → Lawfare Academy
← Computer Science: Algorithms, Systems and Software
Weeks 5–8
Representation, hardware and operating systems
Learning objectives
- Explain the mechanisms and distinctions in representation, hardware and operating systems.
- Apply the assigned concepts to the supplied fictional record and justify each inference.
- Revise a conclusion when evidence, assumptions or constraints change.
Develop the concepts
A computer represents information through physical states interpreted according to an encoding. A bit has two distinguishable values; a sequence of bits can represent numbers, text, instructions or other data depending on conventions. The bit pattern alone does not establish its meaning. Signed integers, unsigned integers and character encodings interpret patterns differently.
Finite representations have limits. An unsigned eight-bit integer represents 256 distinct values, commonly 0 through 255. Arithmetic outside the range may wrap, signal an error or use another rule depending on the language and operation. Floating-point values approximate many real quantities, so equality and accumulation require care. Representation errors are different from an incorrect algorithm, although both can affect the result.
Processors execute instructions while memory and storage provide different capacities, persistence and access costs. Caching exploits locality but introduces coordination concerns. An operating system manages resources, schedules execution and provides abstractions such as processes and files. A process’s apparent private environment depends on isolation mechanisms; it is not an excuse to ignore resource limits. Connect the abstraction visible to a program with the underlying constraints when diagnosing performance, reliability or access problems.
Worked record
A fictional device stores a counter as an unsigned eight-bit value and defines arithmetic modulo 256. The counter is 250 and the program adds 10.
Reason through the record
The mathematical sum is 260, but modulo 256 the stored value is 4. That result follows from the explicitly specified representation rule, not from ordinary unlimited integer arithmetic. A display of 4 can therefore mean overflow rather than a true decrease in the counted event. If the language instead checks overflow and raises an error, the outcome differs. State the storage type and arithmetic semantics before diagnosing the behavior. A safer design might use a wider type, an explicit limit check or a rollover record, depending on the purpose. Testing only small counter values would miss this boundary condition.
Deeper explanation: Bits, ranges, representation and resource boundaries
Bits have no self-announcing type. The same eight bits can represent an unsigned integer, a signed two's-complement integer, a character code or part of a larger value. A file format or protocol supplies the interpretation. Converting bytes to a number requires agreement on width, signedness and byte order. Successfully decoding something does not establish that the chosen interpretation is correct.
For eight-bit unsigned integers, the range is 0 through 255. Two's-complement signed eight-bit integers represent −128 through 127. The high bit has a different weight in the signed interpretation. Arithmetic beyond a representation's range needs a defined policy: reject, widen, saturate, or wrap where the language or operation specifies wrapping. Do not assume that every programming language handles overflow alike. Python's ordinary integers can grow beyond a fixed machine width, while storage formats and external systems may still impose a fixed range.
Binary floating-point represents a finite set of scaled binary values. Many decimal fractions have no exact finite binary expansion. This is a representation issue, not evidence that arithmetic is random. Choose an error tolerance tied to the problem for approximate scientific work. For an integer-cent ledger, parse and validate the input as an exact number of cents and enforce the allowed range. Rounding every intermediate amount can introduce a different error from rounding only the final presentation.
An operating system mediates resources such as memory, files and processes. A process address space is an abstraction; an address meaningful in one process is not automatically a transferable data reference. Persistent storage, process memory and CPU cache have different lifetime and consistency properties. A variable updated in memory can disappear on restart. A file write acknowledged by a high-level function may still differ from a complete durable transaction. A reliable design states which failure boundary its completion signal actually covers.
Fully worked investigation
The byte 11111110 has unsigned value 128+64+32+16+8+4+2 = 254. Under signed eight-bit two's complement it is −128+64+32+16+8+4+2 = −2. The bytes 01 00 interpreted as an unsigned 16-bit integer give 256 in big-endian order and 1 in little-endian order. Neither interpretation is inherently visible in the bytes; the surrounding format must specify it.
Independent transfer problem
Interpret 10000001 as unsigned and signed eight-bit two's complement. Then specify an input contract for integer cents that rejects fractional cents and values outside −1,000,000 through +1,000,000. Name three boundary tests.
Reasoning and limitations
The unsigned value is 129 and the signed value is −127. An exact-cent contract validates representation and range before mutation; it rejects a fractional-cent input rather than silently truncating it. Test exactly −1,000,000, exactly +1,000,000 and one value just outside the range; also test a fractional amount and malformed text.
Unit 2: information, hardware and operating-system boundaries
Information requires an encoding
A physical device distinguishes states; an encoding gives those distinctions a meaning. One bit has two possible values. With n independent bit positions, there are 2ⁿ possible patterns. That count alone does not say whether the patterns denote characters, signed numbers, instructions or colors. A byte commonly contains eight bits. A protocol can combine bytes into a larger value, but must specify order, width and interpretation. The retained native byte/endianness investigation develops those calculations fully.
Text introduces another layer. A character repertoire identifies abstract characters; an encoding maps them to code units or bytes. Unicode code points are not interchangeable with a count of displayed glyphs, and a variable-width encoding such as UTF-8 need not use one byte per character. A format must also describe field boundaries: the adjacent strings '12' and '3' become ambiguous as '123' unless length, delimiters or another framing rule distinguishes them. A delimiter requires escaping or another rule when the delimiter itself appears in the data. Compression reduces size for suitable data by exploiting structure; lossless decoding recovers the original represented data, while lossy coding deliberately discards information. Encryption serves a different purpose and does not guarantee compression or correct authorization.
Binary arithmetic follows positional weights just as decimal arithmetic does, with a different base. For a fixed-width unsigned result, the representable range is finite. A language or interface must define what happens outside that range. Signedness changes interpretation, not the physical bit pattern. Binary floating point represents a finite selection of scaled values, so a decimal quantity can be rounded on conversion and at later arithmetic steps. Display rounding is distinct from changing the underlying stored value. Choose tolerances or exact representations from the application's meaning, rather than testing approximate scientific quantities and exact account balances with one universal equality rule.
Logic, state and instruction execution
A Boolean AND operation is true only when both inputs are true; OR is true when at least one is true; NOT reverses a Boolean value. These functions can be combined into circuits. XOR is true when two Boolean inputs differ. For a one-bit addition with inputs a and b and no incoming carry, the sum bit is a XOR b and the carry bit is a AND b. For inputs 00, 01, 10, 11, the respective sum/carry outputs are 00, 10, 10, 01, where the first output position denotes the sum bit. State the order explicitly: concatenating these two outputs in the opposite order changes how the result is read.
Combinational logic computes outputs from current inputs. Sequential state elements retain information across steps, allowing a later result to depend on earlier events. A simplified processor contains registers, an arithmetic/logic unit and control machinery. Its program counter identifies an instruction position under the architecture's rules. A conceptual instruction cycle fetches an encoded instruction, decodes it, obtains operands, performs an operation and updates state. Actual processors can overlap and reorder internal work while preserving their architecture's required observable behavior. A higher clock frequency alone therefore does not determine an application's execution time.
In a load/store architecture, arithmetic operates on register values while explicit load and store instructions move data between memory and registers. This is an architectural example, not a rule for every instruction set. Consider the conceptual sequence load r1 from X; add immediate 3 to r1; store r1 to Y. If X contains 5, the resulting Y is 8 under sufficient-width integer arithmetic. That trace leaves X unchanged and says nothing about persistence after power loss. Machine instruction semantics, memory visibility and storage durability remain separate layers.
Memory hierarchy and locality
Registers, caches, main memory and persistent storage differ in capacity, access cost and lifetime. A cache keeps copies of selected data so repeated access can avoid a more expensive level. Temporal locality concerns reuse over time; spatial locality concerns nearby locations. A cache hit is useful only if the copy satisfies the consistency rules required for the operation. More cache capacity does not repair an application that accepts stale permission information or assumes a volatile write is durable.
An average-access calculation needs a precise event definition. In a fictional model, every request spends 1 time unit checking a cache; a miss then requires an additional 20 units to retrieve the value. With an 80% hit rate, average cost is 1+0.2×20=5 units per access. It is not 0.8×1+0.2×20=4.8, because the latter incorrectly omits the initial lookup cost on misses. If 'miss cost 20' had instead been explicitly defined as the total cost including lookup, then 4.8 would match that different model. A correct equation depends on the measured boundary, not merely on familiar symbols.
Processes, threads and scheduled execution
A program stored as instructions becomes a process when executed with its own execution state and managed resources. A process can contain multiple threads that share an address space while maintaining separate execution contexts such as registers and stacks. Concurrency means tasks have overlapping lifetimes; parallelism means work actually executes simultaneously on available resources. On a single execution core, interleaving can create concurrency without simultaneous instruction execution by those tasks.
The operating system schedules runnable work and arranges for blocked work to wait for events such as input completion. A context switch saves enough execution state to resume another task. A timer interrupt can return control to the kernel even when an application does not voluntarily yield. A system call is a controlled request for an operating-system service; it is not the same as an ordinary call to any function in a library. Privilege modes and controlled entry points help keep an application from simply performing arbitrary kernel operations.
Scheduling involves tradeoffs among response time, throughput and fairness. A long computation can delay a short interactive task under one policy, while very frequent switching consumes resources under another. A blocked task is not necessarily ready to run merely because it has existed for a long time. Queue length by itself cannot diagnose whether a system is CPU-bound, waiting on storage or constrained by another service. Observe the resource and interval that the claim concerns.
Address translation, files and failure boundaries
A virtual address is interpreted within an address-space context. Hardware and operating-system mechanisms translate permitted addresses to physical storage and enforce access rules. Two processes can use the same numeric virtual address for different underlying data. A page table records mappings at a page granularity; a translation cache can avoid repeating some lookup work. A page fault transfers control to the operating system to handle an absent or disallowed mapping. It does not always mean that the machine must read a page from disk: the fault can require another action, or be an invalid access that cannot be satisfied.
Memory isolation protects boundaries but does not make an application's own data structures correct. Threads sharing writable state still need appropriate synchronization. If two threads both read counter 10, each computes 11 and each writes 11, one logical increment is lost. The problem is not solved by declaring the variable shared. Use a suitable atomic operation or protected critical section under the platform's memory model; a sleep inserted between operations is not a correctness mechanism.
A file interface names and accesses persistent data through operating-system abstractions. Opening a file creates a resource that should be closed, but closing alone is not a universal promise of power-loss durability or multi-file atomicity. Buffering can postpone work, and device/operating-system guarantees matter. A successful write, a synchronized durable write and a database commit answer different questions. The retained transaction investigation adds the requirement that linked state changes and their evidence remain consistent after failure.
Original worked record and changed resource model
The fictional Harbor service handles 1000 requests. At the measured cache boundary, 800 hit and 200 miss. Each incurs the 1 unit lookup and each miss adds 20 units, giving 1000+4000=5000 units total. A proposed change raises the hit count to 950, reducing the same access cost to 1000+1000=2000 units, a 60% reduction for that component. It is not automatically a 60% reduction for the whole service. If other work consumes 5000 unchanged units, total service cost falls from 10000 to 7000, a 30% reduction under this additive model.
Changed facts: the new cache requires 4000 units to rebuild for each 1000 request batch, and that rebuilding was excluded from the reported 2000. The changed total becomes 2000+4000+5000=11000 units, exceeding the original 10000. A repeated warmed-cache benchmark would miss the actual rebuild workload. If a stale cached value also directs a request to a resource the actor cannot access, rejecting unauthorized access is required regardless of the apparent speed gain. Reconcile correctness, construction cost, reuse interval and memory cost before recommending the cache.
Optional address-space practice with full model
Question: a fictional byte-addressed machine has 256 byte pages. Process P reads virtual address 0x0314. Its virtual page 3 maps to physical frame 9. Calculate the page offset and physical byte address under the supplied mapping, and explain why process Q cannot automatically use the same address to obtain the same data.
Model: 0x0314 is 788 decimal. Dividing by 256 gives page 3 with offset 20. Frame 9 begins at 9×256=2304, so the physical address is 2324 decimal, or 0x0914. Process Q has its own mapping and permissions; the same numeric virtual address can map elsewhere or be invalid. The calculation does not itself grant read permission. Changed facts: P's page-table entry is present but marked non-readable. The translation arithmetic may still identify a frame, but the access is disallowed; it must not be reported as a successful read. A permission fault and an absent-page fault are distinct cases even when both transfer control to the operating system.
Complete original cumulative application and rubric: https://www.lawfaregroup.com/knowledge/academy/developed-studies/computing-contracts-machines-and-evidence.html#cumulative
Apply the idea
A fictional device stores a counter as an unsigned eight-bit value and defines arithmetic modulo 256. The counter is 250 and the program adds 10.
The counter is changed to a checked sixteen-bit integer. Is unlimited counting now guaranteed?
Additional worked record — a separate fictional scenario: The byte 11111110 has unsigned value 128+64+32+16+8+4+2 = 254. Under signed eight-bit two's complement it is −128+64+32+16+8+4+2 = −2. The bytes 01 00 interpreted as an unsigned 16-bit integer give 256 in big-endian order and 1 in little-endian order. Neither interpretation is inherently visible in the bytes; the surrounding format must specify it.
Progressive transfer problem: Interpret 10000001 as unsigned and signed eight-bit two's complement. Then specify an input contract for integer cents that rejects fractional cents and values outside −1,000,000 through +1,000,000. Name three boundary tests.
Read the worked reasoning
No. The available range grows, but remains finite, and checked overflow introduces an explicit failure condition. Calculate the relevant limit and design how the system should handle it rather than assume that a larger representation removes all bounds.
Transfer reasoning: The unsigned value is 129 and the signed value is −127. An exact-cent contract validates representation and range before mutation; it rejects a fractional-cent input rather than silently truncating it. Test exactly −1,000,000, exactly +1,000,000 and one value just outside the range; also test a fractional amount and malformed text.
Check understanding
Why can 11111110 mean either 254 or −2?
- Signedness changes the weights assigned to the same bits
Feedback
Correct. Unsigned and signed two's-complement encodings interpret the leading bit differently.
- The computer changes the physical bits during every read
Feedback
Incorrect. No physical change is required. Interpretation is supplied by the type or format.
- Endianness alone changes an eight-bit value
Feedback
Incorrect. Byte order concerns the order of multiple bytes. Signedness explains this single-byte example.
Further reading
Study the complete native lesson and matching original on-site reader unit with the preserved quantitative investigation, then the complete Harbor cumulative case and rubric. All practice, local laboratory execution and publisher chapters are optional; no external learning departure is required.