简体   繁体   English

将uint8_t数组转换为uint16_t

[英]Convert uint8_t array to uint16_t

I have a uint8_t array that contains two elements: 我有一个uint8_t数组,其中包含两个元素:

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. 我想从这两个uin8_t值中获取一个uint16_t数字(而不是数组)。 I used this approach in order to get this result: uint16_t ui16 = 6070 我使用这种方法以获得结果: uint16_t ui16 = 6070

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

But I got uint16_t ui16 = 15430; 但是我得到uint16_t ui16 = 15430;

Am using the wrong method to get what I need? 使用错误的方法来获取我所需要的吗? Or is there something missing? 还是缺少一些东西?

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. 如果要使用十进制数,则需要将“ MSB”乘以100并将其相加。 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). 请不要在两种情况下都将“ 70”放在“ 60”之前,因为您要移动数组的第一个元素(70)。 The 70 will be the MSB. 70将是MSB。

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; }
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中,可以执行以下操作:

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. 您可以使用类似的逻辑从uint8_t数组写入uint32_t / uint64_t。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM