您的位置:首页 > 其它

UVA 128 - Software CRC

2014-03-06 13:09 288 查看
给出一串字符串,求其循环冗余校验码.

求法:把整个字符串看成一个整数m,第一个字符作为这个整数的最高字节,第二个字符作为次高字节,etc...

要求在这个整数最后加上两个字节变成m2,使其整除34943.

解法:快速幂取模,粒度为一个字节.

#include <cstdio>
#include <string.h>
using namespace std;
#define MOD 34943
char message[1025];

int mod_pow(int a, int b, int c){
int res = 1, t = a;
while(b){
if(b & 1)res = res * t % c;
t = t * t % c;
b >>= 1;
}
return res % c;
}

int main(){
while(gets(message)){
if(message[0] == '#' && message[1] == 0)break;
int ans = 0, len = strlen(message), shift = 2;
for(int i = len - 1; i >= 0; --i){
ans = (ans + message[i] * mod_pow(256, shift, MOD) % MOD) % MOD;
shift++;
}
ans = (MOD - ans) % MOD;
printf("%02X %02X\n", ans >> 8, ans & ((1 << 8) - 1));
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: