Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert uint8_t array to uint16_t

Tags:

c

I have a uint8_t array that contains two elements:

uint8_t ui8[2]; // uint8_t array
ui8[0] = 70; // LSB
ui1[1] = 60; // MSB

I want to get a uint16_t number (not an array) from these two uin8_t values. I used this approach in order to get this result: uint16_t ui16 = 6070

uint16_t ui16 = ui8[1] | (ui8[0] << 8);

But I got uint16_t ui16 = 15430;

Am using the wrong method to get what I need? Or is there something missing?

like image 277
Pryda Avatar asked Jul 13 '26 23:07

Pryda


1 Answers

Maybe you meant to work with hexadecimal numbers :

uint8_t ui8[2]; // uint8_t array
ui8[0] = 0x70; // LSB
ui1[1] = 0x60; // MSB

uint16_t ui16 = ui8[1] | (ui8[0] << 8);
printf("%x\n", ui16); // 7060

If you want to work with decimal number, when you need to multiply the "MSB" by 100 and add them. It's far more uncommon to work with decimal number for that.

uint8_t ui8[2]; // uint8_t array
ui8[0] = 70; // LSB
ui1[1] = 60; // MSB

uint16_t ui16 = ui8[1] + (ui8[0] * 100);
printf("%d\n", ui16); // 7060

Please not than in both case, "70" will be before the "60", because you're shifting the first element of the array (70). The 70 will be the MSB.

like image 109
blue112 Avatar answered Jul 16 '26 12:07

blue112