1.数据来源
2.实验结果
checksum : 0110100100010010 check the checksum : 1111111111111111
3.C++代码
#include<iostream>
#include<string>
using namespace std;
int n = 14, m = 16;
string a[14] = {
"1001100100010011",
"0000100001101000",
"1010101100000011",
"0000111000001011",
"0000000000010001",
"0000000000001111",
"0000010000111111",
"0000000000001101",
"0000000000001111",
"0000000000000000",
"0101010001000101",
"0101001101010100",
"0100100101001110",
"0100011100000000"
};
int str2int(string s) {
int res = 0;
for (auto c : s) {
res = (res << 1) + c - '0';
}
return res;
}
string int2str(int x) {
string res;
for (int i = m - 1; i >= 0; i--) {
if (((x >> i) & 1) == 1)res.push_back('1');
else res.push_back('0');
}
return res;
}
int add(int x, int y) {
int res = x + y;
if (((res >> m) & 1) == 1) {
res -= (1 << m);
res += 1;
}
return res;
}
string get_checksum() {
int res = 0;
for (int i = 0; i < n; i++) {
res = add(res, str2int(a[i]));
}
return int2str(~res);
}
string check_checksum() {
int res = 0;
for (int i = 0; i < n; i++) {
res = add(res, str2int(a[i]));
}
return int2str(res);
}
int main() {
string checksum = get_checksum();
cout <<"checksum : " <<checksum << endl;
a[9] = checksum;
cout <<"check the checksum : "<< check_checksum() << endl;
return 0;
}
|