calculating cyclic redundancy codes
In Description computer network, cyclic redundancy code is used to verify the correctness of the data. The principle is that the sender calculates the cyclic redundancy code of the binary data to be sent, and sends it along with the original data to the receiver, and the receiver computes the received data by re-calculating the cyclic redundancy code and comparing it with the received cyclic redundancy code, if the two are the same, the data received is correct, otherwise the data is wrong. The calculation of cyclic redundancy codes for binary data is as follows:
1. Agreement prior to a binary generation of the expression, the subject is set to 10011;
2. Add 4 0 to the end of the binary data string to be sent,
3. The data string of 0 will be added in addition to the generated expression, the remainder;
2. The remainder is the cyclic redundancy code for this binary data string.
For example:
The data string is: 1101011011 The
generated expression is: 10011
cyclic redundancy code: 1110
The calculation process is as follows:
According to the above calculation method, write a cyclic redundancy code calculation program, assuming that the length of the binary data string is not more than 20 bits, the generated expression is fixed to 10011.
The first line of input inputs contains a positive integer k (1<=k<=10), which indicates the number of test cases. followed by the K line, each line corresponds to a test example, containing an N-bit binary string (1<=n<=20), representing the data.
Output each Test example corresponds to a row of outputs, with a 5-bit binary string that represents the cyclic redundancy code.
Sample Input 2110101101110101010
Sample Output 0111001001 problem solving ideas:
Simulation. AC Code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
Char str[30];
Char b[]= "10011";
int main () {
int T;
scanf ("%d", &t);
while (t--) {
getchar ();
scanf ("%s", str);
strcat (str, "0000");
int len = strlen (str);
for (int i = 0; i < len-4; ++i) {
if (str[i] = = ' 0 ')
continue;
int k = i;
for (int j = 0; j < 5; ++j,++k) {
if (Str[k]^b[j])
str[k] = ' 1 ';
else
str[k] = ' 0 ';
}
}
for (int i = len-5; i < Len; ++i)
printf ("%c", Str[i]);
printf ("\ n");
}
return 0;
}