Swap Byte Order of a 32-bit Value
Write uint32_t bswap32(uint32_t x) that reverses the byte order (0x11223344 becomes 0x44332211), and uint32_t load_be32(const uint8_t *p) that reads a big-endian 32-bit value from a byte buffer, correctly on any host and at any alignment.
Write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Move each byte to its new position with shifts and masks. For load_be32, build the value byte by byte instead of casting the pointer.
#include <stdio.h>
#include <stdint.h>
uint32_t bswap32(uint32_t x)
{
return (x >> 24) |
((x >> 8) & 0x0000FF00u) |
((x << 8) & 0x00FF0000u) |
(x << 24);
}
uint32_t load_be32(const uint8_t *p)
{
return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 |
(uint32_t)p[2] << 8 | (uint32_t)p[3];
}
Casting buf + 1 to uint32_t * would be both an unaligned access (HardFault on Cortex-M0) and a strict-aliasing violation, and it would still give the wrong answer on a little-endian host. Assembling from bytes is portable and the compiler turns it into LDR + REV where the hardware allows.
Note the casts to uint32_t before shifting: p[0] promotes to int, and 0xDE << 24 overflows a signed int.
Show the hidden tests
/* ---- tests ---- */
static int fails;
#define CHECK(c) do { if (!(c)) { printf("FAIL line %d: %s\n", __LINE__, #c); fails++; } } while (0)
int main(void)
{
CHECK(bswap32(0x11223344u) == 0x44332211u);
CHECK(bswap32(0x000000FFu) == 0xFF000000u);
CHECK(bswap32(bswap32(0xDEADBEEFu)) == 0xDEADBEEFu);
uint8_t buf[] = { 0x00, 0xDE, 0xAD, 0xBE, 0xEF };
CHECK(load_be32(buf + 1) == 0xDEADBEEFu); /* unaligned */
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}