Format Bytes as a Hex and ASCII Dump
WaymoSoftware Engineer · OnsiteLast updated
This problem tests string manipulation, modular arithmetic, and careful handling of formatting constraints to produce a standardized hexadecimal memory dump.
Problem Statement
Implement a function format_hex_dump(data: bytes, width: int = 16) -> str that converts a byte string into a formatted hex dump. Each line represents a chunk of width bytes.
Formatting Rules
- Offset: The start of each line must show the 8-digit hexadecimal offset (e.g.,
00000000). - Hex Columns: Follow the offset with space-separated hex values. If a line has fewer than
widthbytes, pad the missing columns with spaces to maintain alignment. Use two lowercase hex digits per byte. - ASCII Column: Add a vertical bar
|after the hex section, followed by the printable ASCII representation of the bytes. If a byte is not a printable ASCII character (defined as space0x20through tilde0x7E), display a period.instead. - Alignment: Ensure the ASCII section is always the same width, even if the last line is partial.
Constraints
widthwill be a multiple of 4, typically 16.- Input
datalength can be from 0 to 10,000 bytes.
Example
Input: data = b'Hello, World!', width = 8
Output:
00000000 48 65 6c 6c 6f 2c 20 57 |Hello, W|
00000008 6f 72 6c 64 21 |orld! |
Edge Cases
- Empty input
b''. - Data length exactly divisible by
widthvs. remainder cases. - Handling non-printable characters (e.g.,
0x00,0x1F,0x7F).
Hints
Hint 1
Process the byte array in slices of size `width` and track the current offset counter.
Hint 2
For each slice, generate hex strings using `'{:02x}'.format(b)` and convert characters to '.' if they are outside the range 32-126.
Hint 3
To pad the hex section, calculate the number of missing bytes and add three spaces (two for hex digits plus one separator) for each missing byte.
Follow-up questions
- How would you modify this to handle streaming input where data is provided in chunks rather than a single byte array?
- If you needed to output this to a file instead of a string to save memory, what design changes would you implement?
- How would the logic change if you wanted to display the hex in groups of 4 bytes instead of individually?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.