gpt4 book ai didi

c - 如何以小端顺序发送数据 C

转载 作者:行者123 更新时间:2023-12-03 22:54:41 26 4
gpt4 key购买 nike

我正在与要求我向其发送 2 个有符号字节的板进行通信。

数据类型说明
enter image description here我需要发送什么 enter image description here

我需要按位操作还是可以像下面这样发送 16 位整数?

int16_t rc_min_angle = -90; 
int16_t rc_max_angle = 120;

write(fd, &rc_min_angle, 2);
write(fd, &rc_max_angle, 2);

最佳答案

int16_t 具有正确的大小,但可能是也可能不是正确的字节顺序。为确保小端顺序使用宏,例如来自 endian.h 的宏:

#define _BSD_SOURCE
#include <endian.h>

...

uint16_t ec_min_angle_le = htole16(ec_min_angle);
uint16_t ec_max_angle_le = htole16(ec_max_angle);

write(fd, &ec_min_angle_le, 2);
write(fd, &ec_max_angle_le, 2);

这里 htole16 代表“host to little endian 16-bit”。它将主机的 native 字节顺序转换为小字节序:如果机器是大字节序,它交换字节;如果它是小端字节序,则它是空操作。

另请注意,您将值的地址传递给 write(),而不是值本身。遗憾的是,我们无法内联调用并编写 write(fd, htole16(ec_min_angle_le), 2)

关于c - 如何以小端顺序发送数据 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54013771/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com