English 中文(简体)
Compute Arithmetic Sum to Communicate with Machine Over Serial
原标题:
  • 时间:2010-01-06 16:23:24
  •  标签:
  • c++
  • checksum

I am communicating with a machine over serial. Part of the protocol communication spec states that the control sum is an "arithmetic sum of bytes from < PS > (included), < data > to < CS >"

The packet messages are structured as follows:

< PS >< data >< CS >, where:

< PS > - Packet Size

Length: 1

Value: 0x02 to 0x63

Max packet length is 99 bytes

< data > - Data

Length: 1...90 bytes

Value: 0x00 - 0xFF

The length of the data part depends on the command.

< CS > - Check Sum

Length - 1 byte

Value: 0x00 - 0xFF

Example:

ACK Packet: 0x02 0x01 0x03 where 0x03 is the checksum.

So how do I compute the checksum for these bytes in C++?

最佳回答

It looks like the checksum is a simple sum, modulo 256.

int sum = 0;
for (int j = 0;  j < number_of_bytes_in_message;  ++j)
   sum += message [j];

sum %= 256;  // or, if you prefer  sum &= 255;
问题回答

Use an unsigned 8-bit type (uint8_t or unsigned char) as an accumulator, add each byte to it as you generate the packet, then send it as the checksum byte. Exactly how depends on how you intend to construct the packets.





相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签