user1377493 user1377493 - 8 months ago 56
C Question

cast uint8_t array to uint32_t array, alignment is off

I am trying to cast a uint8_t array to uint32_t array. However, when i try to do this, I cant seem to be able to access every consecutive 4 bytes.

Let us say I have a uint8_t array with 8 bytes. I would like to access byte 2 -> 6 as one uint32_t.

These all get the same value


gets the bytes 4 -> 8 as expected.

So it seem like I can not access 4 consecutive bytes from any address?

Is there any way that I can do this?


If you want bytes 2..6, you're going to have to combine multiple aligned loads to get what you want.

uint32_t *ptr = ...;
uint32_t value = (ptr[0] >> 16) | (ptr[1] << 16);

Technically, this is also the portable way to do things in C in general, but we're all spoiled because you don't have to do the extra work on x86, ARM, Power, or other common architectures.