Jesper Evertsson Jesper Evertsson - 23 days ago 5x
C Question

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.


This should do it:

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