user1377493 user1377493 - 1 month ago 16
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

*((uint32_t*)&uint8Array[0])
,
*((uint32_t*)&uint8Array[1])
,
*((uint32_t*)&uint8Array[2])
,
*((uint32_t*)&uint8Array[3])


While
*((uint32_t*)&uint8Array[4])
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?

Answer

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.