ContentsFoundations to FrontierBezhig

code/solutions/representation_lab.py

All lab code. Download this file.

"""C09.05: explicit representations and a direct-mapped cache simulator."""
import struct

def signed8(bits: int) -> int:
    if type(bits) is not int or not 0 <= bits <= 255:
        raise ValueError("one byte required")
    return bits if bits < 128 else bits - 256

def float32_bits(value: float) -> str:
    raw = struct.unpack(">I", struct.pack(">f", value))[0]
    return f"{raw:032b}"

def cache_misses(addresses: list[int], line_bytes: int = 64,
                 slots: int = 4) -> int:
    if line_bytes <= 0 or slots <= 0:
        raise ValueError("positive geometry required")
    tags: list[int | None] = [None] * slots
    misses = 0
    for address in addresses:
        if type(address) is not int or address < 0:
            raise ValueError("nonnegative integer byte address required")
        block = address // line_bytes
        slot = block % slots
        if tags[slot] != block:
            misses += 1
            tags[slot] = block
    return misses

if __name__ == "__main__":
    print(signed8(254), float32_bits(1.0))
    print(cache_misses([0, 4, 64, 0, 256, 0]))