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();
};
Run Code Online (Sandbox Code Playgroud)
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?
}
Run Code Online (Sandbox Code Playgroud)
Please help. I am new to C++ and C.
您可以使用 IPv4 标头中使用的校验和,它是 16 位:
http://en.wikipedia.org/wiki/IPv4_header_checksum
或查看 CRC16:http : //en.wikipedia.org/wiki/Crc16
如果你在谷歌上搜索一下,你可以找到更多的算法:
http://en.wikipedia.org/wiki/List_of_hash_functions
http://en.wikipedia.org/wiki/Category:Checksum_algorithms
要实现您的功能,只需首先依次转换您的每对字符String message
并将其提供给校验和算法。
如果您有奇数个字节,则必须正确填充最后一个字节(检查您选择的单个算法的文档,或者只计算最后一对的 16 位值,因为最后一个缺少的字符为零)。
处理完消息后,将序列号添加到 has 并将校验和结果存储在checksum
变量中。
如果您想测试您是否在此过程中犯了错误,许多算法(循环)在对包括其 CRC 在内的整个消息进行哈希处理后确实会输出零结果。如果您得到零,则表示消息没有损坏,或者您的算法在您测试时正常工作。
归档时间: |
|
查看次数: |
27301 次 |
最近记录: |