def METHOD_NAME(val: int) -> bytes:
    if not isinstance(val, int):
        raise TypeError("int")
    # base 256, MSB first, two's complement, minimum number of octets
    # necessary. This has a number of annoying edge cases:
    # * 0 and -1 are 0x00 and 0xFF, not the empty string.
    # * 255 is 0x00 0xFF, not 0xFF
    # * -256 is 0xFF 0x00, not 0x00
    # Special-case to avoid an empty encoding.
    if val == 0:
        return b"\x00"
    sign = 0  # What you would get if you sign-extended the current high bit.
    out = b""
    # We can stop once sign-extension matches the remaining value.
    while val != sign:
        byte = val & 0xFF
        out = struct.pack("!B", byte) + out
        sign = -1 if byte & 0x80 == 0x80 else 0
        val >>= 8
    return out