How do i combine two uint16_t value ?

if you can see im converting my input data2 to hex using uint16_t LSB and uint16_t MSB. how do I save that two value as one single unsigned long val . then I can return that variable. I think using sprintf method is wrong as it does show just char representation? please kindly correct me this if I'm wrong?

unsigned long PrintHex32( uint32_t data) // prints 32-bit data in hex with leading zeroes
{
  uint32_t data2 = data << 8;
  //char tmp[16];
  uint16_t LSB = data2 & 0xffff;
  uint16_t MSB = data2 >> 16;
   unsigned long  val = xxxx(uint16_t LSB) + uint16_t MSB(YYY);
  //sprintf(tmp, "0x%.4X%.4X%", MSB, LSB);
  return val ;
}

@OP

Say, you have passed data = 0x12345678 (32-bit)

You have shifted data to the left by 8-bit; now, you expect to get: 1234567800 which is 40-bit. You are saving the shifted data into variable data2 by the following code:

uint32_t data2 = data << 8;

What is the present content of data2? Is it not 34567800? If so, you are loosing information. You need to do something so that the information 1234567800 is preserved? Or, it is fine if you know what you are doing.

2 16-bit values into 1 32-bit value is easily done by doin a bitwise 'OR' like this

uint16_t msw, lsw;
uint32_t val32=(uint32_t)  msw<<16 | lsw;

keep in mind that any value you shift should still fit into the variable used for calculation (hence the cast of msw into 32 bit)

1 Like