</>EmbeddedInterview

How do you swap the endianness of a 32-bit value?

EasyPointers & Memory

Short answer: Move each byte to its mirrored position with shifts and masks, or use the compiler built-in __builtin_bswap32(), which compiles to a single REV instruction on Arm. For network code use htonl()/ntohl(), which swap only when the host is little-endian.

#include <stdint.h>

static inline uint32_t bswap32(uint32_t x)
{
    return  (x >> 24)               |
           ((x >>  8) & 0x0000FF00u) |
           ((x <<  8) & 0x00FF0000u) |
            (x << 24);
}

static inline uint16_t bswap16(uint16_t x)
{
    return (uint16_t)((x >> 8) | (x << 8));
}
/* bswap32(0x12345678) == 0x78563412 */

Use unsigned types. A version written with int:

int a = 0x12345678, out = 0;
out |= (a & 0x000000ff) << 24;   /* 0x78 << 24 sets the sign bit of int: overflow, UB */
out |= (a & 0xff000000) >> 24;   /* for a negative a, >> is implementation-defined */

works on most compilers for this particular value, but it relies on undefined and implementation-defined behaviour. With uint32_t every shift is well-defined.

Other ways

Method Notes
__builtin_bswap16/32/64 GCC/Clang; one instruction on Arm (REV, REV16), x86 (BSWAP)
__REV(), __REV16(), __REVSH() CMSIS intrinsics for Cortex-M
htonl, htons, ntohl, ntohs POSIX/socket APIs: host ↔ network (big-endian)
htobe32, le32toh (<endian.h>) Linux/BSD: explicit target byte order
cpu_to_be32, le32_to_cpu Linux kernel; also annotate types (__be32) so sparse can check
Shifts from a byte array best for parsing buffers (also avoids alignment problems)

The pattern most firmware should use: do not swap integers in place. Convert at the boundary: parse incoming bytes with get_be32(buf) and serialise outgoing data with put_be32(buf, v). That handles byte order and alignment in one step and works unchanged on any CPU.