Array of byte array in int

I have an array of four bytesand want to pass it to int. The following code only works for this:

#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 will be as expected:

$./test
0xdeadc0de

Now I want to do this in one layer, for example:

#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 leads to:

$./test
0x1

Why is my program behaving like this?

+4
source share
2 answers

You mix operators for boolean or ( ||) and 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]);
+4
source

Logical OR ||is different from bitwise OR|

So in the second snippet you use ||use|

+4
source

Source: https://habr.com/ru/post/1616691/


All Articles