Insert an array of hex codes into an integer

I'm trying to do something that, in my opinion, would be pretty simple, but I'm just ignoring something obvious or it is actually a bit complicated. My problem: I have a 4 character array that contains 4 hexadecimal values. For instance:

array[0] = 0xD8
array[1] = 0xEC
array[2] = 0xA2 
array[3] = 0x83

I want to store this array as an integer with a combined value, in this case 0xD8ECA283

I tried doing a logical OR, and then changing the bits, and with this method I was able to save the value 0xD8 in an integer, but not otherwise. Any advice would be appreciated.

+4
source share
2 answers

This should do it:

int i;
int combined = 0;
for (i = 0; i < 4; i++) {
    combined = (combined << 8) | ((unsigned char) array[i]);
}
+4
source

, 32 , unsigned long ( uint_least32_t).

, undefined / , .

.

unsigned long a = ( ( ( unsigned long )array[0] & 0xFF ) << 24 ) |
                  ( ( ( unsigned long )array[1] & 0xFF ) << 16 ) |
                  ( ( ( unsigned long )array[2] & 0xFF ) << 8 ) |
                  ( ( ( unsigned long )array[3] & 0xFF ) << 0 ) ;

( unsigned long ), int.
& 0xFF ( , CHAR_BIT!= 8).

+5

All Articles