UDP 计算校验和

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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值