Home | Projects | Notes > Coding Interview Questions > Switching Endianness

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.

 

A Naive Macro Implementation

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.

Problems with the Naive Approach

1. Multiple Evaluation of the Argument

Macros do not protect against multiple evaluations of their arguments.

This results in undefined behavior and subtle bugs. In safety-critical or embedded systems, this is unacceptable.

2. Missing Type Safety

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.

3. Reduced Readability

A one-line bitwise expression is harder to read, review, and maintain, especially in large firmware projects.

Improved Solution

 

A Safer and More Readable Solution

In real-world embedded code, a static inline function is usually preferred over a macro as it offers safety without sacrificing performance.

Why This is Better