Checksum in C++
You could use check sum used in IPv4 header, it's 16bit:
http://en.wikipedia.org/wiki/IPv4_header_checksum
Or check out CRC16: http://en.wikipedia.org/wiki/Crc16
You could find more algorighms if you googled a bit around:
http://en.wikipedia.org/wiki/List_of_hash_functions
http://en.wikipedia.org/wiki/Category:Checksum_algorithms
To implement your function, just first sequentially convert every pair of characters in your String message
and feed it to the checksum algorithm.
If you have an odd number of bytes, you have to zero pad the last byte properly (check docs for your individual algorithm you did choose, or just compute the 16bit value of the last pair as the last missing character was zero).
After you have processed the message, add the seq number to the has and store your checksum result in your checksum
variable.
If you want to test if you did a mistake in the process, many algorithms (cyclic) do output zero result after you hashed the whole message including its CRC. If you get zero it means the message is not corrupt or your algorithm works correctly when you test it.
user899714
Updated on July 09, 2022Comments
-
user899714 almost 2 years
I need help with writing a code in C++ to do a 16 bit checksum.
The idea is to get data input from user (a string), convert it to binary form, then calculate checksum and put it in my data packet. I don't have any checksum type specification... I thought XORing the 16 bits would be a good idea. I have the following class packet given:
class packet { private: string message; unsigned int checksum; // this is a 16 bit checksum unsigned int seqNum; public: packet(string str, unsigned int seq); void setMessage(string str); void setSeqNum(unsigned int num); string getMessage(); int getLength(); unsigned int calculateChecksum(); int getChecksum(); bool getSeqNum(); };
I have to calculate my checksum here given the above:
packet::packet(string str, unsigned int seq) { this->message = str; this->seqNum = seq; // calculate checksum here checksum = calculateChecksum(); //HOW TO CODE THIS FUNCTION? }
Please help. I am new to C++ and C.