Convert Bytes to Int / uint in C

There’s no standard function to do it for you in C. You’ll have to assemble the bytes back into your 16- and 32-bit integers yourself. Be careful about endianness!

Here’s a simple little-endian example:

extern uint8_t *bytes;
uint32_t myInt1 = bytes[0] + (bytes[1] << 8) + (bytes[2] << 16) + (bytes[3] << 24);

For a big-endian system, it’s just the opposite order:

uint32_t myInt1 = (bytes[0] << 24) + (bytes[1] << 16) + (bytes[2] << 8) + bytes[3];

You might be able to get away with:

uint32_t myInt1 = *(uint32_t *)bytes;

If you’re careful about alignment issues.

Leave a Comment