Hardware interview practice
Detect machine endianness in C
Implement detect_endian() without undefined behavior. Inspect the stored bytes of a multi-byte unsigned integer whose value is 1.
Starting point
Question code
enum endian { LITTLE, BIG, UNKNOWN };
enum endian detect_endian(void);Reviewed example
Work through one case
Input
bytes of uint32_t value 1 are 01 00 00 00Expected output
LITTLEThe least-significant byte is stored at the lowest address.
What to cover
Requirements
- Inspect object representation only through an unsigned char pointer.
- Return LITTLE when the first byte is 1 and BIG when the last byte is 1.
- Return UNKNOWN for any other representation.
- Do not infer memory byte order by shifting the numeric value.
