Reputation: 71
So I have a Raspberry Pi reading CAN Data from a vehicle. If I use the candump
program included in canutils
I get a bunch of data, an example look like:
can0 1C4 [8] 03 F3 26 08 00 00 7F 70
I then wrote a simple C++ app to open a socket to the can0
bus and read some data into a char buffer. If I loop through each character of the buffer after a read and convert each char to an int in hex format (and put a pipe in between each char) I get the following:
c4|1|0|0|8|0|0|0|3|f3|26|8|0|0|7f|70|
My question is, why is the ID byte reversed when I read the data using a socket and a char buffer? This behavior is consistent with all CAN ID's. The Data Length code and the Data is in the correct format/order but the ID backward.
Thanks, Adam
Upvotes: 5
Views: 6643
Reputation: 40160
Congratulation, you just discovered 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).
As a convention, network (including bus) data is big endian. Your PC architecture is probably little endian.
In order to fix this, pass your data to ntoh*()
functions to reverse its byte order (if necessary) from network (n
) to host (h
) endianness.
Upvotes: 8