8 years, 6 months ago.

how to merge two hex variable into one hex variable.

Any idea how to merge two hex variable, 0F and CE into one hex variable that result in "0FCE"???
When it is printf("%.4X", one_hex_variable), the result will be 0FCE.

#include "mbed.h"

Serial device(p9,p10) // tx, rx
char a[8];

int main()
{
    device.baud(xxxx);
    device.putc(xxxx); //And more putc...
    for(int x = 0; x < 8; x++) { //Device will transmit back 9 hex value, I only need a[5] and a[6].
    a[x] = device.getc();
    wait_ms(1);
    }
    printf("%.2X,%.2X\n", a[5], a[6]); //Results: a[5] = 0F, a[6] = CE
}

1 Answer

8 years, 6 months ago.

the simple & dirty would be ..

  pc.printf ("%02x%02x", a[5], a[6]);

or ..

int Result;
Result = a[5];
Result = Result << 8;
Result = Result | a[6];

pc.printf ("%04x",Result);

or

union
{
  int result;
  char b[2];
} U;
{

U.b[0] = a[6];
U.b[1] = a[5];

pc.printf ("%04x",U.result);
}

Hope this helps

Ceri

Accepted Answer