#include
#include
#include
#include
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;
}