gpt4 book ai didi

c++ - 为什么从 Socket 读取时 CAN BUS Frame ID 是反的?

转载 作者:搜寻专家 更新时间:2023-10-31 01:31:05 26 4
gpt4 key购买 nike

所以我有一个 Raspberry Pi 从车辆读取 CAN 数据。如果我使用 canutils 中包含的 candump 程序,我会得到一堆数据,示例如下:

can0 1C4 [8]  03 F3 26 08 00 00 7F 70

然后我编写了一个简单的 C++ 应用程序来打开到 can0 总线的套接字并将一些数据读入字符缓冲区。如果我在读取后遍历缓冲区的每个字符并将每个字符转换为十六进制格式的 int(并在每个字符之间放置一个管道),我得到以下结果:

c4|1|0|0|8|0|0|0|3|f3|26|8|0|0|7f|70|

我的问题是,当我使用套接字和字符缓冲区读取数据时,为什么 ID 字节会反转?此行为与所有 CAN ID 一致。数据长度代码和数据的格式/顺序正确,但 ID 倒序。

谢谢,亚当

最佳答案

恭喜,您刚刚发现了endianness .

Endianness refers to the sequential order in which bytes are arranged into larger numerical values, when stored in computer memory or secondary storage, or when transmitted over digital links. Endianness is of interest in computer science because two conflicting and incompatible formats are in common use: words may be represented in big-endian or little-endian format, depending on whether bits or bytes or other components are ordered from the big end (most significant bit) or the little end (least significant bit).

作为惯例,网络(包括总线)数据是大端。您的 PC 架构可能是小端。

为了解决这个问题,请将您的数据传递给 ntoh*()函数将其字节顺序(如有必要)从网络 (n) 反转为主机 (h) 字节顺序。

关于c++ - 为什么从 Socket 读取时 CAN BUS Frame ID 是反的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46404723/

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