您的位置:首页 > 其它

uvaoj 138 Software CRC 大数取模

2015-01-06 19:03 162 查看
uvaoj 138 Software CRC 大数取模
求循环冗余检验(CRC)的值,循环冗余检验在计算机网络中应该提到过,计算的方法差不多。不过这里固定了要在后边加上2个字节的数,加上两个字节后,就组成了一个很大的整数,这个整数要处理34943为0,我们就设计算出来的检验位为x,原数为n,那么合起来的数为m=(n<<16)+x,那么m%34943=0,也就是((n<<16)%34943+x%34943)%34943=0,则可以得x=(34943-(n<<16)%34943%34943。因为数比较大,所以要一个字节一个自己的取模,可能中间结果超过int,要使用64位整数。
代码如下:
/*************************************************************************
> File Name: 128.cpp
> Author: gwq
> Mail: gwq5210@qq.com
> Created Time: 2015年01月06日 星期二 11时39分02秒
************************************************************************/

#include <cmath>
#include <ctime>
#include <cctype>
#include <climits>
#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <map>
#include <set>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>

#define INF (INT_MAX / 10)
#define clr(arr, val) memset(arr, val, sizeof(arr))
#define pb push_back
#define sz(a) ((int)(a).size())

using namespace std;
typedef set<int> si;
typedef vector<int> vi;
typedef map<int, int> mii;
typedef long long ll;

const double esp = 1e-5;

string tohex(ll n)
{
string mp = "0123456789ABCDEF";
int a = (n >> 12) & ((1 << 4) - 1);
int b = (n >> 8) & ((1 << 4) - 1);
int c = (n >> 4) & ((1 << 4) - 1);
int d = n & ((1 << 4) - 1);
string ret = "";
ret += mp[a];
ret += mp[b];
ret += " ";
ret += mp[c];
ret += mp[d];
return ret;
}

int main(int argc, char *argv[])
{
ll m = 34943;
string str;
while (getline(cin, str)) {
if (str[0] == '#') {
break;
}
ll len = str.length();
ll res = 0;
for (int i = 0; i < len; ++i) {
res = ((res << 8)  + str[i]) % m;
}
res = (res << 16) % m;
res = (m - res) % m;
cout << tohex(res) << endl;
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: