Write a high-performance parser that takes a binary telemetry packet, given as a list of integers where each integer is one byte (0 to 255), and converts it into a structured dictionary using bitwise operations.
The packet layout, with bytes numbered from 0:
-
Bytes 0-1: packet ID, a 16-bit unsigned integer in big-endian order.
-
Byte 2: version in the upper 4 bits and priority in the lower 4 bits.
-
Bytes 3-6: timestamp, a 32-bit unsigned integer in big-endian order.
-
Byte 7: payload length
N
.
-
Bytes 8 to
8 + N - 1
: the payload bytes.
-
Byte
8 + N
: checksum, the XOR of all preceding bytes (bytes 0 through
8 + N - 1
).
Return a dictionary with the keys "packet_id", "version", "priority", "timestamp", "payload" (a list of ints) and "valid" (a boolean that is true when the checksum matches).
If the packet is too short to hold the minimum header (9 bytes), or the declared payload length exceeds the available data, return a dictionary with every numeric field set to 0, "payload" set to an empty list and "valid" set to False.
Function Signature
def parse_telemetry(packet: list[int]) -> dict:
Rules
-
A packet is malformed when
len(packet) < 9
or
len(packet) < 9 + N
, where
N = packet[7]
. Both the payload and the checksum byte must fit. A malformed packet returns
{"packet_id": 0, "version": 0, "priority": 0, "timestamp": 0, "payload": [], "valid": False}
.
-
Bytes after the checksum byte at index
8 + N
are ignored.
-
A well-formed packet whose checksum does not match still returns its decoded fields, with
"valid"
set to
False
.
Constraints
-
1 <= len(packet) <= 1024
-
0 <= packet[i] <= 255
-
0 <= N <= 255
(the payload length in byte 7)
Examples
Input: packet = [0, 42, 83, 0, 0, 3, 232, 3, 10, 20, 30, 182]
Output: {"packet_id": 42, "version": 5, "priority": 3, "timestamp": 1000, "payload": [10, 20, 30], "valid": False}
The header decodes to packet ID 42, version 5 and priority 3 (byte 2 is 0x53), timestamp 0x000003E8 = 1000, and a 3-byte payload. The XOR of bytes 0 through 10 is 145, which differs from the checksum byte 182, so "valid" is False.
Input: packet = [1, 0, 33, 0, 0, 0, 1, 0, 33]
Output: {"packet_id": 256, "version": 2, "priority": 1, "timestamp": 1, "payload": [], "valid": True}
The packet ID is (1 << 8) | 0 = 256, byte 2 is 0x21 (version 2, priority 1), the timestamp is 1 and the payload is empty. The XOR of bytes 0 through 7 is 1 ^ 33 ^ 1 = 33, which matches byte 8.
Input: packet = [0, 1, 16, 0, 0, 0, 5, 4, 7, 8]
Output: {"packet_id": 0, "version": 0, "priority": 0, "timestamp": 0, "payload": [], "valid": False}
Byte 7 declares a 4-byte payload, so a complete packet needs 8 + 4 + 1 = 13 bytes. Only 10 are present, so the packet is malformed and the default dictionary comes back.