Exercise 3 solution def decode_signed(raw): value = int.from_bytes(raw, "big") bits = len(raw) * 8 if value >= 1 << (bits - 1): value -= 1 << bits return value def encode_signed(value, size): if value < 0: value += 1 << (size * 8) return value.to_bytes(size, "big") for n in range(-128, 128): raw = encode_signed(n, 1) assert raw == n.to_bytes(1, "big", signed=True) assert decode_signed(raw) == n print("all 256 one-byte values agree") # all 256 one-byte values agree print(decode_signed(b"\xff\xfe"), encode_signed(-2, 2).hex(" ")) # -2 ff fe print(decode_signed(b"\x80\x00\x00\x00"), encode_signed(-1, 4).hex(" ")) # -2147483648 ff ff ff ff (Run as written; the output matched the comments.) Explanation: in two's complement, a pattern whose top bit is set stands for the unsigned value minus 2**bits. Decoding subtracts 2**bits when the value is at or above 2**(bits - 1); encoding adds 2**bits to a negative number so it fits in the unsigned range. The loop checks both functions against Python's own signed=True handling for every possible one-byte value.