KatInterview

Parse Mixed-Endian Binary Protocol Fields

Math & Bit ManipulationAuto-graded · 14 test cases
MediumAuto-gradedMath & Bit Manipulationbit-manipulationbytesendianness

Last updated

Tests byte-level manipulation to extract little-endian and big-endian integers from a raw byte buffer without relying on architecture-specific memory layout.

You're implementing a binary protocol parser that needs to extract fields from incoming network packets. The protocol uses a mixed-endian format where different fields are encoded with different byte orders.

Each packet consists of a 12-byte header with the following structure:

  • Bytes 0-1: magic number (big-endian, not needed for this problem)
  • Bytes 2-3: command identifier (16-bit unsigned integer, little-endian)
  • Bytes 4-7: payload length (little-endian, not needed for this problem)
  • Bytes 8-11: timestamp (32-bit unsigned integer, big-endian)

Write a function that takes a byte buffer representing the packet header and returns the command identifier and timestamp as a list of two integers.

Input Format:

  • packet: a list of integers representing bytes (each in range 0-255), length exactly 12

Output Format:

  • A list of exactly two integers: [command_id, timestamp]

Byte Order Reminder:

  • Little-endian: least significant byte first (e.g., [0x34, 0x12] → 0x1234)
  • Big-endian: most significant byte first (e.g., [0x12, 0x34] → 0x1234)

Constraints

  • Input list has exactly 12 elements
  • Each element is an integer in range [0, 255]
  • Command identifier fits in 16 bits (0 to 65535)
  • Timestamp fits in 32 bits (0 to 4294967295)

Examples

Example 1

Input: parse_protocol_fields([170, 85, 52, 18, 4, 0, 0, 0, 1, 2, 3, 4])

Output: [4660, 16909060]

Example 2

Input: parse_protocol_fields([170, 85, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255])

Output: [65535, 4294967295]

Hints

Hint 1

Little-endian means the first byte is the least significant: multiply it by 1, the second by 256.

Hint 2

Big-endian means the first byte is the most significant: multiply it by 256^3, then 256^2, then 256, then 1.

Hint 3

Use bitwise OR and left shifts to combine bytes into integers without overflow issues.