APDR

Computer Exercise 3: Worked solutions

Algorithms, Programming, and Data Representation · Module 92313 · Exercise 3

Manual byte decoding, packet layouts, checksums, stream recovery, address translation, and round trips. Try each task before opening its worked steps. Personalized inputs and results are omitted; apply the methods to your own assigned data.

Task 1: Decode an unsigned integer

Task 01 · Decode an unsigned integer

Try first: Decode bytes manually in big-endian order, without int.from_bytes.

Attempted it? Open the worked steps

Task 01 · worked solution

  1. Start with value 0. For every byte, shift the accumulated value left by 8 bits, then OR in the new byte.

  2. For bytes 0x12, 0x34 the calculation is (0 × 256 + 18) × 256 + 52 = 4660. This is positional notation in base 256.

  3. Empty input naturally returns 0. Reject any endianness label other than big or little.

  4. Reference implementation:

    def bytes_to_uint(data, endianness="big"):
        if endianness == "big":
            value = 0
            for byte in data:
                value = (value << 8) | byte
            return value
        if endianness == "little":
            return sum(byte << (8 * i) for i, byte in enumerate(data))
        raise ValueError("endianness must be big or little")

Task 2: Decode a signed two’s-complement integer

Task 02 · Decode a signed two’s-complement integer

Try first: Decode the unsigned bit pattern, then interpret its top bit as the sign.

Attempted it? Open the worked steps

Task 02 · worked solution

  1. For w bits, first compute the unsigned value u. If the high bit is 0, the signed value is u; otherwise subtract 2^w.

  2. For the one-byte pattern 11111101, u = 253 and w = 8, so the value is 253 − 256 = −3.

  3. The range is −2^(w−1) through 2^(w−1)−1. Check the all-zero and all-one patterns.

  4. Reference implementation:

    def bytes_to_int_twos_complement(data, endianness="big"):
        value = bytes_to_uint(data, endianness)
        width = 8 * len(data)
        if width and value & (1 << (width - 1)):
            value -= 1 << width
        return value

Task 3: Decode IEEE 754 single precision

Task 03 · Decode IEEE 754 single precision

Try first: Separate sign, exponent, and fraction bits, then apply the normal or subnormal formula.

Attempted it? Open the worked steps

Task 03 · worked solution

  1. A binary32 word has 1 sign bit, 8 exponent bits, and 23 fraction bits. For a normal number, value = (−1)^s × (1 + fraction/2^23) × 2^(exponent−127).

  2. If exponent is zero, use the subnormal significand fraction/2^23 and exponent −126, with no implicit leading one.

  3. Exponent 255 represents infinity when fraction is zero and NaN otherwise. Require exactly 4 bytes and verify endianness first.

  4. Reference implementation:

    def bytes_to_float32(data, endianness="big"):
        if len(data) != 4:
            raise ValueError("float32 requires exactly 4 bytes")
        bits = bytes_to_uint(data, endianness)
        sign = -1 if bits >> 31 else 1
        exponent, fraction = (bits >> 23) & 255, bits & 0x7fffff
        if exponent == 255:
            return sign * float("inf") if fraction == 0 else float("nan")
        if exponent == 0:
            return sign * (fraction / 2**23) * 2**-126
        return sign * (1 + fraction / 2**23) * 2**(exponent - 127)

Task 4: Infer byte order from a known range

Task 04 · Infer byte order from a known range

Try first: Decode the same bytes both ways and use a plausible range to choose the unique match.

Attempted it? Open the worked steps

Task 04 · worked solution

  1. Compute big- and little-endian candidates independently.

  2. A candidate matches when lower ≤ value ≤ upper. Return an order only if exactly one candidate matches; neither or both is ambiguous and should raise ValueError.

  3. Test boundary values inclusively and include an ambiguous example.

  4. Reference implementation:

    def detect_endianness(raw, known_field_range):
        lower, upper = known_field_range
        big = lower <= bytes_to_uint(raw, "big") <= upper
        little = lower <= bytes_to_uint(raw, "little") <= upper
        if big == little:
            raise ValueError("range does not identify unique byte order")
        return "big" if big else "little"

Task 5: Parse a mixed packet layout

Task 05 · Parse a mixed packet layout

Try first: Walk declared fields in order, consuming padding and decoding each field by its specified type.

Attempted it? Open the worked steps

Task 05 · worked solution

  1. Track a byte offset. For each field, slice exactly its width and advance the offset, including for padding.

  2. Decode uint, int, float32, or bytes using that field’s endianness; padding produces no output key. Reject negative widths, truncated fields, and unknown types.

  3. Check a layout with one padding byte and mixed-endian fields.

  4. Reference implementation:

    def parse_packet(raw, layout):
        result, offset = {}, 0
        for field in layout:
            width = field["width"]
            end = offset + width
            if width < 0 or end > len(raw): raise ValueError("field exceeds packet")
            data, offset = raw[offset:end], end
            kind = field["type"]
            order = field.get("endianness", "big")
            if kind == "padding": continue
            if kind == "uint": value = bytes_to_uint(data, order)
            elif kind == "int": value = bytes_to_int_twos_complement(data, order)
            elif kind == "float32": value = bytes_to_float32(data, order)
            elif kind == "bytes": value = data
            else: raise ValueError(f"unsupported field type: {kind}")
            result[field["name"]] = value
        return result

Task 6: Validate an additive checksum

Task 06 · Validate an additive checksum

Try first: Recompute a modulo-256 sum over payload bytes and compare the final byte.

Attempted it? Open the worked steps

Task 06 · worked solution

  1. For packet bytes b0 … bn, the expected checksum is sum(b0 … bn−1) mod 256.

  2. In Python, sum(raw[:-1]) & 0xff keeps the low eight bits. Require a nonempty packet before indexing its last byte.

  3. A checksum detects many accidental changes but is not authentication; distinct corruptions can collide.

  4. Reference implementation:

    def validate_checksum(raw):
        return bool(raw) and (sum(raw[:-1]) & 0xff) == raw[-1]

Task 7: Decode a stream and keep going after errors

Task 07 · Decode a stream

Try first: Process packets independently, validate before parsing, and record failures by their original index.

Attempted it? Open the worked steps

Task 07 · decode_stream(packets) · worked solution

  1. Enumerate the input so each packet keeps its original zero-based index. Check the checksum before trying to parse its payload.

  2. For a good checksum, parse the packet bytes before the final checksum byte. Catch malformed packet errors for this packet, record them, and continue the loop.

  3. Return successful decoded packets and indexed errors separately. A corrupt packet must not prevent later packets from being decoded.

  4. The stream decoder, using Tasks 5 and 6:

    def decode_stream(packets, layout):
        decoded, errors = [], []
        for index, packet in enumerate(packets):
            try:
                if not validate_checksum(packet):
                    raise ValueError("invalid checksum")
                decoded.append(parse_packet(packet[:-1], layout))
            except Exception as error:
                errors.append({"index": index, "error": str(error)})
        return {"decoded": decoded, "errors": errors}

Task 8: Translate virtual addresses

Task 08 · PageTableSim

Try first: Split an address into its virtual page and within-page offset, then map the page to a physical frame.

Attempted it? Open the worked steps

Task 08 · PageTableSim · worked solution

  1. Require a positive page size and retain the supplied page table. Use divmod(virtual_addr, page_size) to obtain the virtual page number and offset.

  2. If the page has frame number f, the physical address is f × page_size + offset. If the page is absent, raise PageFaultError instead of inventing a mapping.

  3. Check the first and last address in a page, a mapped page with a nonzero offset, and an unmapped page that must raise the fault.

  4. The simulator:

    class PageFaultError(Exception):
        pass
    
    class PageTableSim:
        def __init__(self, page_size, page_table):
            if page_size <= 0:
                raise ValueError("page_size must be positive")
            self.page_size = page_size
            self.page_table = page_table
    
        def translate(self, virtual_addr):
            page, offset = divmod(virtual_addr, self.page_size)
            if page not in self.page_table:
                raise PageFaultError(f"virtual page {page} is unmapped")
            return self.page_table[page] * self.page_size + offset

Task 9: Simulate first-fit heap allocations

Task 09 · Simulate first-fit heap allocations

Try first: Allocate each request from the first free block large enough, returning its start and size or None.

Attempted it? Open the worked steps

Task 09 · worked solution

  1. This function accepts allocation sizes but has no free operation, so the free memory remains one contiguous suffix starting at next_address.

  2. First-fit therefore succeeds when next_address + size is within the pool, returns that range, and advances the address. Otherwise it records None. Reject negative pool and request sizes.

  3. Check that successful ranges do not overlap, remain within the pool, and that a failed request does not move the next address.

  4. Reference implementation:

    def simulate_heap_alloc(requests, pool_size):
        if pool_size < 0: raise ValueError("pool_size cannot be negative")
        allocations, next_address = [], 0
        for size in requests:
            if size < 0: raise ValueError("allocation size cannot be negative")
            if next_address + size <= pool_size:
                allocations.append((next_address, size))
                next_address += size
            else:
                allocations.append(None)
        return allocations

Task 10: Check integer encode/decode round trips

Task 10 · Check integer encode/decode round trips

Try first: Encode a value at a chosen width and verify decoding in each byte order returns it.

Attempted it? Open the worked steps

Task 10 · worked solution

  1. For an unsigned width w bytes, valid values satisfy 0 ≤ value < 28w. Validate width, value, and endianness before encoding.

  2. Emit bytes from most significant to least significant for big-endian, and reverse that order for little-endian.

  3. Round-trip zero, the maximum representable value, and a value with distinct bytes. The decoder should reproduce the original integer.

  4. Reference implementation:

    def uint_to_bytes(value, width, endianness="big"):
        if endianness not in ("big", "little") or width < 0:
            raise ValueError("invalid encoding parameters")
        if value < 0 or value >= 1 << (8 * width):
            raise ValueError("value does not fit")
        shifts = range(width - 1, -1, -1) if endianness == "big" else range(width)
        return bytes((value >> (8 * shift)) & 255 for shift in shifts)
    
    def roundtrip_test(value, endianness, width):
        encoded = uint_to_bytes(value, width, endianness)
        return bytes_to_uint(encoded, endianness) == value

Personal worked solutions based on the APDR Computer Exercise 3 sheet, explained in my own words. Examples are generic; use your own assigned inputs for any personalized result. Not an official FAU publication; check course details against current materials. Made by Thanate Amornjiraporn (Focus).