Pryda
Pryda

Reputation: 1029

Convert uint8_t array to uint16_t

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?

Upvotes: 3

Views: 16722

Answers (3)

0___________
0___________

Reputation: 68013

you can also use union punning for it:

#include <stdio.h>
#include <stdint.h>

typedef union {
    uint8_t u8[2];
    uint16_t u16;
}data16;

int main() {
    data16 d16;

    d16.u8[0] = 0x60;
    d16.u8[1] = 0x70;

    printf("%hx\n", d16.u16);

    // it works in the opposite direction as well
    // lets try to store 7060 decimal in two bytes

    d16.u16 = 7060u;

    printf("storing %hu decimal in two bytes: LSB:0x%0hhx (%hhu decimal), MSB:0x%0hhx (%hhu decimal)\n", d16.u16, d16.u8[0], d16.u8[0], d16.u8[1], d16.u8[1]);

    return 0; }

Upvotes: 5

cpp_enthusiast
cpp_enthusiast

Reputation: 1299

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

To copy the both values into a uint16, you can do as below:

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

You can use the similar logic for writing the uint32_t/uint64_t from the array of uint8_t.

Upvotes: 1

blue112
blue112

Reputation: 56572

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.

Upvotes: 7

Related Questions