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

标签 c endianness

我正在与要求我向其发送 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/

相关文章:

c - Makefile 和 "relocation has invalid symbol index"错误

c - 如何抑制coverity警告 "CHECKED_RETURN"

在位域结构上转换字节序(再次)

endianness - 字节序背后的原因?

c - C 二进制文件的位字节顺序和可移植性

c - #define, EQ(a, b) ((a) == (b)) 是什么意思?

C:指向数组的指针和字符数组

c++ - 使用 strlen 时不为空终止符添加 +1 会导致在使用 send 时发送额外的垃圾字节

java - 如何将 int 转换为字节数组(这是一个局部变量),无论底层硬件的字节顺序如何都保证相同的结果

C-如何使变量成为大端。默认情况下?