C语言 将两个 uint8_t 组合为 uint16_t

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15249791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:35:26  来源:igfitidea点击:

Combining two uint8_t as uint16_t

c

提问by johan

I have the following data

我有以下数据

uint8_t d1=0x01; 
uint8_t d2=0x02; 

I want to combine them as uint16_tas

我想将它们组合uint16_t

uint16_t wd = 0x0201;

How can I do it?

我该怎么做?

回答by md5

You can use bitwise operators:

您可以使用按位运算符:

uint16_t wd = ((uint16_t)d2 << 8) | d1;

Because:

因为:

 (0x0002 << 8) | 0x01 = 0x0200 | 0x0001 = 0x0201

回答by R.. GitHub STOP HELPING ICE

The simplest way is:

最简单的方法是:

256U*d2+d1

回答by Lundin

This is quite simple. You need no casts, you need no temporary variables, you need no black magic.

这很简单。你不需要强制转换,不需要临时变量,不需要黑魔法。

uint8_t d1=0x01; 
uint8_t d2=0x02; 
uint16_t wd = (d2 << 8) | d1;

This is always well-defined behavior since d2 is always a positive value and never overflows, as long as d2 <= INT8_MAX.

这始终是明确定义的行为,因为 d2 始终是正值并且永远不会溢出,只要d2 <= INT8_MAX.

(INT8_MAX is found in stdint.h).

(INT8_MAX 可在 stdint.h 中找到)。

回答by fizzbuzz

(uint16_t)((d2 << 8) + (d1 & 0x00ff))