简体   繁体   English

无符号int转换C ++

[英]Unsigned int conversion C++

I'm trying to figure out a serial program with C++. 我正在尝试找出一个使用C ++的串行程序。 I'm sending a char array that consists of several uint8_t and several uint16_t that I'm trying to split up and send. 我正在发送一个char数组,该数组由几个uint8_t和几个uint16_t组成,我试图将它们拆分并发送。

char buf[3];
uint16_t var=1500;

What's the difference (if any) between these: 这些之间有什么区别(如果有):

buf[0]= var & 0xFF; buf[1]= var >> 8;

and

buf[0]= (uint8_t)(var & 0xFF); buf[1]= var >> 8;

The other end is expecting 16bit integers with LSB first and for some reason I just don't think I'm getting the expected serial write. 另一端期望首先使用LSB的16位整数,由于某种原因,我只是不认为自己得到了预期的串行写入。 I know there are a multitude of reasons this could be happening, but I'm just trying to wrap my head around the concept here. 我知道发生这种情况的原因有很多,但是我只是想在这里围绕这一概念进行探讨。

Most serial protocols want data in big-endian order. 大多数串行协议都需要大端顺序的数据。 In that case you should just do *reinterpret_cast<short*>(buf) = htons(var) . 在这种情况下,您只需要执行*reinterpret_cast<short*>(buf) = htons(var) If you really need little-endian, use htole16 , defined in string/endian.h . 如果你真的需要小端,使用htole16 ,定义string/endian.h

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

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