I work a lot with byte buffers and have to extract different parts. In this example, it’s 4 byte, but it ranges from a single bit to 128 bit. Speed is the most important metric here. See the code for a MWE. I’d like to know if there is a better way.
#include <stdint.h> static uint32_t get_data(uint8_t *buf, size_t off) { return ((uint32_t)(buf[off + 0]) << 24) + ((uint32_t)(buf[off + 1]) << 16) + ((uint32_t)(buf[off + 2]) << 8) + ((uint32_t)(buf[off + 3])); } int main(int argc, char **argv) { uint8_t buf[128]; /* get some example data */ for (uint8_t i = 0; i < 128; ++i) buf[i] = i; /* we want the data from offset 10 as an uint32_t */ uint32_t res = get_data(buf, 10); }