Hex Codec (C)
Topics: bit manipulation, encoding
Problem
Implement hexadecimal encode and decode over caller-provided buffers — no
allocation. Encoding emits lowercase; decoding accepts either case.
size_t hex_encode(const unsigned char *in, size_t inlen, char *out, size_t outcap);
long hex_decode(const char *in, size_t inlen, unsigned char *out, size_t outcap);
hex_encode: each byte becomes two lowercase hex digits (high nibble first):
out[2i] = HEX[byte >> 4], out[2i+1] = HEX[byte & 0xF]. NUL-terminate; return
the length (excluding the NUL), or 0 if out is too small.
hex_decode: input length must be even; each digit pair becomes one byte
((hi << 4) | lo). Return the byte count, or -1 on malformed input (odd length
or a non-hex character) or if out is too small.
Key concepts
- Nibbles: a byte is two 4-bit halves. Encoding splits
>> 4 and & 0xF;
decoding recombines (hi << 4) | lo.
- Validate the digit map: map
0-9, a-f, A-F to 0-15 and reject anything
else — don't silently treat a bad character as zero.
- Odd length is malformed: hex always comes in pairs.
Run
cc -std=c11 -O2 -Wall tests.c -o /tmp/hex && /tmp/hex
Sign in to submit your solution.