Abu - 1 year ago 111
C Question

# convert signed integer array in big endian to hexa decimal 16 bit in little endian in c

I am new to the endians.
I am trying to convert a big endian integer array to hexadecimal string in little endian. I tried to convert big endian integer array to little endian hexa decimal string. But at the end, getting big endian hexa decimal encoded string instead of little endian. Please help me

``````gint16 frame[5] = {10, -26, 35, 7, -35};  //big endian
gint16 frame_i[5];
size_t i;
for (i= 0; i < 5; i++) {
frame_i[i] = (frame[i] << 8) | ((frame[i] >> 8) & 0xFF);  //big endian to little endian
}
char *str = malloc(5 * 4 + 1);
size_t j;
for (j= 0; j < 5; j++) {
snprintf(str + j * 4, 5, "%04X", frame_i[j] & 0xFFFF); // getting big endian  instead of little endian
}
``````

The expression `(frame_i[i] << 8) | ((frame_i[i] >> 8) & 0xFF);` has no effect (you would have noticed that, if you had used `-Wall` compiler option). Also, you should apply this operation on the `frame` variable, and store the result in `frame_i`, e.g.:

``````int16_t frame[5] = {10, -26, 35, 7, -35};
int16_t frame_i[5] = {0};
size_t i;

for (i = 0; i < sizeof(frame) / sizeof(int16_t); i++) {
frame_i[i] = (frame[i] << 8) | ((frame[i] >> 8) & 0xFF);
}

for (i = 0; i < sizeof(frame) / sizeof(int16_t); i++) {
printf("%04X -> %04X\n", frame[i] & 0xFFFF, frame_i[i] & 0xFFFF);
}
``````

Output

``````000A -> 0A00
FFE6 -> E6FF
0023 -> 2300
0007 -> 0700
FFDD -> DDFF
``````

Note, as @WeatherVane has pointed out, the right shift of a negative signed integer has implementation-defined behavior. See answers to this question. Consider using an unsigned type, e.g. `uint16_t` from `stdint.h`.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download