在arduino中将两个uint8字节转换为uint16字节的最佳方法是什么?

What is best way to convert two uint8 bytes to uint16 byte in arduino?

我正在使用带 ESP32 的 Arduino,我仍处于初学者水平。我有两个字节,它们是 uint8 并且是变量,我想将它们转换为 uint16。哪种方式最好?我觉得bitshift应该不错

uint8_t first = 0xFF; //lets assume its variable, not constant
uint8_t second = 0xEE;
uint16_t combined = (first << 8) + second;
Serial.println(combined, HEX); // prints FFEE

上面的代码可以完成工作,但我不确定它是否是 right/best 方式。

Which way would be best to do it? I think bitshift should be good

对于 32 位 int/unsigned,以下所有功能都是相同的,编译器可以发出相同的代码。

uint8_t first, second;
...
uint16_t combined = (first << 8) + second;
uint16_t combined = (first << 8) | second;
uint16_t combined = (first << 8) ^ second;
uint16_t combined = (first * 256) + second;
uint16_t combined = (first * 256) | second;
....

"best" 可能是 "any of the above",因为编译器是一个很好的编译器。

对我来说,如果我觉得编译器可能很弱,我会编写如下代码。

uint16_t combined = ((unsigned)first << 8) | second;

否则我会编码成对更大的代码和清晰度有意义的。如果本质上是算术,则如下:

uint16_t combined = (first * 256u) + second;  // recommended

最后,我可能会尝试 union 技巧来强制进行弱编译,但这种微优化的性能优势与维护工作相比是可疑的。


使用 16 位 int/unsigned,最好避免 int 溢出。

uint16_t combined = ((uint16_t)first << 8) | second;
uint16_t combined = (first * 256u) + second;