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.
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).
This should do it:
int i;
int combined = 0;
for (i = 0; i < 4; i++) {
combined = (combined << 8) | ((unsigned char) array[i]);
}
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