I have an array of four bytes
and want to cast it to an int
. The following code works just fine for that:
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint8_t array[4] = {0xDE, 0xAD, 0xC0, 0xDE};
uint32_t myint;
myint = (uint32_t)(array[0]) << 24;
myint |= (uint32_t)(array[1]) << 16;
myint |= (uint32_t)(array[2]) << 8;
myint |= (uint32_t)(array[3]);
printf("0x%x\n",myint);
return 0;
}
The result is as expected:
$./test
0xdeadc0de
Now I want to do this in a one-liner like this:
#include <stdio.h>
#include <stdint.h>
int main(void) {
uint8_t array[4] = {0xDE, 0xAD, 0xC0, 0xDE};
uint32_t myint = (uint32_t)(array[0]) << 24 || (uint32_t)(array[1]) << 16 || (uint32_t)(array[2]) << 8 || (uint32_t)(array[3]);
printf("0x%x\n",myint);
return 0;
}
But this results in:
$./test
0x1
Why does my program behave like this?
Your are mixing up the operators for the logical or (||
) and the bit wise or (|
).
Do
uint32_t myint = (uint32_t)(array[0]) << 24
| (uint32_t)(array[1]) << 16
| (uint32_t)(array[2]) << 8
| (uint32_t)(array[3]);
Logical OR ||
is different from bitwise OR |
So in your 2nd snippet you use ||
use |
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With