← All problems · Protocols & Parsing
Decode an Unaligned Big-Endian Word
Read four available bytes as a big-endian uint32_t without casting the buffer to a word pointer.
Implement uint32_t read_be(const uint8_t *p).
Choose C or C++ and write your code on the right and press Run (or Ctrl + Enter). Hidden tests check your functions and print the result below the editor.
Shift each byte into its destination position.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
uint32_t read_be(const uint8_t *p)
{
return ((uint32_t)p[0]<<24)|((uint32_t)p[1]<<16)|((uint32_t)p[2]<<8)|p[3];
}
#include <cstdio>
#include <cstdint>
#include <cstddef>
#include <cstring>
std::uint32_t read_be(const std::uint8_t *p)
{
return ((std::uint32_t)p[0]<<24)|((std::uint32_t)p[1]<<16)|((std::uint32_t)p[2]<<8)|p[3];
}
Byte access is alignment-independent and works on either CPU byte order.
solution.c
OutputPress Run to compile and test your code.
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)
{
uint8_t a[]={0x12,0x34,0x56,0x78,0xff};
CHECK(read_be(a)==0x12345678u);
CHECK(read_be(a+1)==0x345678ffu);
puts(fails ? "Some tests failed" : "All tests passed");
return fails != 0;
}