Home | Projects | Notes > Coding Interview Questions > Switching Endianness
In embedded systems and low-level firmware development, handling endianness correctly is essential, especially when dealing with communication protocols, binary file formats, or cross-platform data exchange. Write a macro to switch the endianness of a 32-bit value.
512 3 4 5 At first glance, this macro appears correct. It reverses the byte order of a 32-bit value. However, it has several issues that are worth addressing.
Macros do not protect against multiple evaluations of their arguments.
11SWITCH_ENDIANNESS(i++)This results in undefined behavior and subtle bugs. In safety-critical or embedded systems, this is unacceptable.
The macro does not specify the expected width or signedness of X. Depending on the platform, int may not be 32 bits, and signed shifts may cause issues.
A one-line bitwise expression is harder to read, review, and maintain, especially in large firmware projects.
512 3 4 5
In real-world embedded code, a static inline function is usually preferred over a macro as it offers safety without sacrificing performance.
912
3static inline uint32_t switch_endianness_u32(uint32_t x)4{5 return ((x & 0x000000FF) << 24) | /* byte 0 -> byte 3 */6 ((x & 0x0000FF00) << 8) | /* byte 1 -> byte 2 */7 ((x & 0x00FF0000) >> 8) | /* byte 2 -> byte 1 */8 ((x & 0xFF000000) >> 24) | /* byte 3 -> byte 0 */9}The argument is evaluated exactly once.
The data width is explicit (uint32_t).
Bit masks and shifts are clearer and easier to audit.
The compiler can still inline this function with zero overhead.