1、 编写一个计算机程序用来计算一个文件的16位效验和。最快速的方法是用一个32位的整数来存放这个和。记住要处理进位(例如,超过16位的那些位),把它们加到效验和中。
原理:把要发送的数据看成16比特的二进制整数序列,并计算他们的和。若数据字节长度为奇数,则在数据尾部补一个字节的0以凑成偶数。
例子:16位效验和计算,下图表明一个小的字符串的16位效验和的计算。
为了计算效验和,发送计算机把每对字符当成16位整数处理并计算效验和。如果效验和大于16位,那么把进位一起加到最后的效验和中。
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int main(int argc, void* argv[])
{
//数据写入文件中
ofstream infile("a.txt",ios::out);
if (!infile){
cout << "打开文件失败。";
exit(1);
}
infile << "Hello world." << endl;
//读取文件
infile.close();
ifstream infile2("a.txt");
string line;
getline(infile2, line);
cout << line << endl;
//将数据转换为ASCII后以字节存入数组,并计算字节数
int len = line.length();
int byte[24];
for (int i = 0; i < len; i++){
char ch = line[i];
int asc = ch;
byte[i] = asc;
cout << ch << " 的ASCII码为" << asc << endl;
}
infile2.close();
if (len % 2 != 0) //处理数据的字节数为单数的情况
{
byte[len] = 0;
len += 1;
}
int high = 0, low = 0;
int h_carry = 0, l_carry = 0;
//把ASCII值转换为十六进制
cout << "十六进制:" << "0x";
for (int i = 0; i < len; i++){
stringstream ss;
ss << hex << byte[i];
cout <<ss.str();
if (i % 2 != 0)
cout << " ";
//高八位加高八位
if (i % 2 == 0){
high += byte[i];
if (high > 255){
h_carry += (high / 256);
high %= 256;
}
}
//低八位加低八位
else
{
low += byte[i];
if (low > 255){
l_carry += (low / 256);
low %= 256;
}
}
}
cout << endl;
//处理进位
high += l_carry;
low += h_carry;
stringstream ss;
ss << hex << high;
ss << hex << low;
cout << "校验和:" << ss.str() << endl;
return 0;
}
执行结果