将两个uint8_t合并为uint16_t。

时间:2022-12-13 19:57:47

I have the following data

我有以下数据。

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

I want to combine them as uint16_t as

我想把它们合并成uint16_t。

uint16_t wd = 0x0201;

How can I do it?

我该怎么做呢?

3 个解决方案

#1


30  

You can use bitwise operators:

你可以使用位运算符:

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

Because:

因为:

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

#2


9  

The simplest way is:

最简单的方法是:

256U*d2+d1

#3


5  

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中找到)。

#1


30  

You can use bitwise operators:

你可以使用位运算符:

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

Because:

因为:

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

#2


9  

The simplest way is:

最简单的方法是:

256U*d2+d1

#3


5  

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中找到)。