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

Why is the CAN BUS Frame ID backwards when reading from a Socket?

所以我有一个 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 一致。数据长度代码和数据是正确的 format/order 但 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) 字节顺序。