If you want to manufacture a uint32_t
from 4 uint8_t
, then do just that: manufacture it. Don't try to pull one from something that isn't one by pointer casts. The code you presented will vary in results depending on whether you're platform is little or big endian, not to mention its just plain wrong.
They're both bad. Both samples provided are unsafe no matter what. data alignment requirements are bypassed with such casts. If anything you're casting 'to' requires potentially more restrictive alignment than anything you're casting 'from', you inviting a bus-error. Heed the initial warning. intermediate pointer-to-void simply masks the problem (as it does for most problems).
You want to know what byte is going "where" when you build that uin32_t
.
uint8_t a[4] = {0x01, 0x23, 0x45, 0x67};
uint32_t b = ((uint32_t)a[0] << 24) |
((uint32_t)a[1] << 16) |
((uint32_t)a[2] << 8) |
(uint32_t)a[3];
This will always put the a[0] byte in the high-byte of the target 32bit unsigned, a[1] in the next byte, etc, regardless of endian'ness. b
will always be 0x01234567
.