Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert array of hex codes into an integer

I'm trying to do something that I thought would be pretty basic but either I'm just ignoring something obvious or it is actually a bit tricky. My problem is: I have an array of 4 chars that contains 4 hex values. For example:

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

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

I've tried doing logical OR and then shifting the bits and with this method I managed to store the value of 0xD8 in the integer, but not the rest. Any tips would be appreciated.

like image 792
Jesper Evertsson Avatar asked Jan 09 '23 11:01

Jesper Evertsson


2 Answers

Use the binary OR operator, and an integer whose precision is guaranteed to be at least 32 bits, which is the type unsigned long (although the type uint_least32_t could also be used).

Unsigned integer is used so any potential undefined and/or implementation defined behavior that is present when shifting signed integers is avoided.

This solution is independent of endianness.

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 ) ;

Casts to ( unsigned long ) are made to avoid intermediate implicit conversion to int.
The & 0xFF operation is there to remove unnecessary bits (if there were any in an unlikely scenario where CHAR_BIT != 8).

like image 113
2501 Avatar answered Jan 16 '23 10:01

2501


This should do it:

int i;
int combined = 0;
for (i = 0; i < 4; i++) {
    combined = (combined << 8) | ((unsigned char) array[i]);
}
like image 39
Filipe Gonçalves Avatar answered Jan 16 '23 11:01

Filipe Gonçalves