Godday all.
Could someone please explain the logical difference in these two implementations of a byte-reversing function.
Example 1:
uint32_t byte_reverse_32(uint32_t num) {
static union bytes {
uint8_t b[4];
uint32_t n;
} bytes;
bytes.n = num;
uint32_t ret = 0;
ret |= bytes.b[0] << 24;
ret |= bytes.b[1] << 16;
ret |= bytes.b[2] << 8;
ret |= bytes.b[3];
return ret;
}
Example 2:
uint32_t byte_reverse_32(uint32_t num) {
static union bytes {
uint8_t b[4];
uint32_t n;
} bytes;
bytes.n = num;
uint32_t ret = 0;
ret |= (bytes.b[0] << 24) || (bytes.b[1] << 16) || (bytes.b[2] << 8) || (bytes.b[3]);
return ret;
}
I must be missing something because for the unsigned integer 0xFE12ADCF
the first example correctly gives 0xCFAD12FE
while the second one yields 1
. What am I missing?
By the way, I couldn't figure out how to get '<<' inside the pre+code-tags, hence LSHIFT
. If it's possible to do it, feel free to edit (and comment on how =)).
Thanks.
EDIT: Fixed the bytes
-variable which was never assigned to.