Emanuel Weinsjö
Emanuel Weinsjö

Reputation: 491

How do i calculate the CRC checksum for the following TCP/IP protocol

enter image description here

Here is the following spec.

I use python3 to talk to a server with TCP/IP using a simple protocol as you see in the image.

I wonder how do i calculate the CRC checksum here ?. Its need to be 1 byte as you see in the Command package spec.

Upvotes: 0

Views: 1828

Answers (2)

I presume in Python 3, if you have the packet in bytes, i.e. say packet = bytes(0xF0, 0xF0, 0xDE, 0xAD, 0xBE, 0xEF, 0xDE, 0xAD, 0xBE, 0xEF, 0xF0, 0xF0), the checksum would simply be the least-significant byte of 1's complement of the sum of these bytes, i.e. (0 - sum(packet)) & 0xFF.

Thus, if you have a payload payload, this would be the code to make it into a full packet:

packet = b'\xF0\xF0' + payload + b'\xF0\xF0'
packet += bytes([(0 - sum(packet)) & 0xFF])

Upvotes: 2

Lundin
Lundin

Reputation: 213990

Assuming this thing is the target here. What they probably mean is that you should sum all bytes together but store the result in a 8 bit variable (uint8_t in C). Meaning that this variable will overflow several times and the least significant byte of the data is what you end up with as checksum.

Similar techniques were often used in the 1970s, but then they often inverted the resulting LS byte into one's complement or two's complement. (For example this is how the Motorola S-record and Intel Hex linker formats got their checksums.)


Please note:

  • This is not a CRC. CRC = cyclic redundancy check, the name of an entirely different kind of algorithm, that can be used to calculate checksums. The person who made the manual/protocol is incompetent.
  • 8 bit addition-based checksum is an amateur solution. It mostly just sits there as waste of space, as the probability for missing even simple single bit faults is laughably poor, basically 50/50. This is what data protocols looked like in the 1960s when people didn't know better. If you want any form of data integrity, this won't do.
  • RS-232 in general is an amateur solution, barely any better than raw UART/TTL levels. This 1960s technique lived on because PC:s supported it for quite a while. They don't any longer, they use USB. As for industrial applications, they use RS-422/RS-485 or better yet CAN.

Therefore this product is not "suitable to any industrial automation devices". It shouldn't be used in an industrial environment.

Upvotes: 0

Related Questions