Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast byte array to int

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?

like image 877
Tom Mekken Avatar asked Feb 08 '23 12:02

Tom Mekken


2 Answers

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]);
like image 129
alk Avatar answered Feb 11 '23 01:02

alk


Logical OR || is different from bitwise OR |

So in your 2nd snippet you use || use |

like image 29
Gopi Avatar answered Feb 11 '23 02:02

Gopi