Uva oj 128-software CRC (software CRC)

Source: Internet
Author: User

Time Limit: 3.000 seconds
Time Limit: 3.000 seconds

 

Problem
Problem

you work for a company which uses lots of personal computers. your boss, Dr penny pincher, has wanted to link the computers together for some time but has been unwilling to spend any money on the Ethernet boards you have recommended. you, unwittingly, have pointed out that each of the PCs has come from the vendor with an asynchronous serial port at no extra cost. dr Pincher, of course, recognize S her opportunity and assigns you the task of writing the software necessary to allow communication between PCs.
you work in a company with many pcs. Your boss is Dr. penny pincher. she I want to connect all my computers. Your suggestion is to buy a nic, but she thinks it is too expensive. At this time, you accidentally thought that all these computers come from the same supplier, and there is a serial port for asynchronous communication that can be directly used without spending money. Dr. pincher adopted this idea and asked you to write software for connecting computers (via Serial Asynchronous Communication.

You 've ve read a bit about communications and know that every transmission is subject to error and that the typical solution to this problem is to append some error checking information to the end of each message. this information allows the processing ing program to detect when a transmission error has occurred (in most cases ). so, off you go to the library, borrow the biggest book on communications yo U can find and spend your weekend (unpaid overtime) reading about error checking.
later, you read some data bits during a communication and found that an error occurred during transmission. The traditional method to solve this problem is to add an error verification message after each message. In this way, the software can use the verification information to check whether errors occur during transmission (in most cases, they are valid ). In the next week, you go to the library every day (during free time without overtime) and use the thickest communication books to learn about error verification.

Finally you decide that CRC (cyclic redundancy check) is the best error checking for your situation and write a note to Dr pincher detailing the proposed error checking mechanic noted below.
Finally, you are sure that CRC (Cyclic Redundancy verification) is the best solution to solve the current problem, and submit a description of the error verification mechanism to Dr. Pincher, as follows:

CRC generation
CRC generation

the message to be transmitted is viewed as a long positive binary number. the first byte of the message is treated as the most significant byte of the binary number. the second byte is the next most significant, etc. this binary number will be called "M" (for message ). instead of transmitting "M" you will transmit a message, "m2", consisting of "M" followed by a two-byte CRC value.
transmitted packets it can be regarded as a long binary number. packets the first byte is the highest bit of the entire binary number, followed by 2nd bytes, and so on. Call this binary number "M" (message, message ). Two bytes of CRC must be appended during transmission of M, it is called "m2 ".

The CRC value is chosen so that "m2" when divided by a certain 16-bit value "G" leaves a remainder of 0. this makes it easy for the processing ing program to determine whether the message has been upted by transmission errors. it simply divides any message received ed by "G ". if the remainder of the Division is zero, it is assumed that no error has occurred.
The CRC code selected should enable m2 to be divisible by a 16-bit number "G", so that the receiver software can easily determine whether a message is faulty during transmission. You only need to divide each received message by "g". If the remainder is 0, no error occurs.

You notice that most of the suggested values of "G" in the book are odd, but don't see any other similarities, so you select the value 34943 for "G" (the generator value ).
You do not find any other rule except that most of the recommended "G" values in the book are odd. Therefore, you choose "34943" as the "G" value.

 

Input and Output
Input and Output

You are to devise an algorithm for calculating the CRC value corresponding to any message that might be sent. to test this algorithm you will write a program which reads lines (each line being all characters up to, but not including the end of line character) as input, and for each line calculates the CRC value for the message contained in the line, and writes the numeric value of the CRC bytes (in hexadecimal notation) on an output line. each input line will contain no more than 1024 ASCII characters. the input is terminated by a line that contains a # in column 1. note that each CRC printed shocould be in the range 0 to 34942 (decimal ).
You need to designAlgorithmFor all   Packets Calculate the CRC code. To test your algorithm, you need to writeProgramTo read the strings entered in each line (each line starts from the beginning to the end of the (but not included) Line Break), calculate the CRC value for the messages represented in each line of string, and then output a line accordingly, print the CRC value. Each line cannot contain more than 1024 ASCII characters. A line with the first character # indicates that the input is complete. Note that each CRC value should be in the range of 0 to 34942 (decimal.

 

Sample Input
Input example

This is a test

A
#

 

Sample output
Output example

77 FD
00 00
0C 86

 

Analysis
Analysis

The actual CRC verification code used in communication is much more complex than the one described in the question and involves a wide range of knowledge points. Here we only introduce the question-related algorithms, for more information, see "cyclic redundancy check" (Wikipedia ).

The main algorithm for this question is to regard the string as a long integer and then perform division to obtain the remainder. To put it simply, we need to implement division of large numbers. Let's take a look at the 10-digit system example. Please use a pen to calculate: 2357 limit 6. We only care about the remainder. For the first time, we had 3 interviewers, 3, and the remainder below was 5. For example, we used 5 × 10 + 5 = 55 as the second dividend, and the remainder of 9 was 1; use 1 × 10 + 7 = 17 as the third dividend, with more than 2 operators and 5 operators. Note that the remainder obtained by dividing each bit of the divisor by the divisor 6 is accumulated to the next bit (multiply by 10 and then add the next bit ). As long as each digit in the divisor is greater than the divisor, you can avoid the occurrence of a bid. The division of the PEN calculation is extended to the n-base system to obtain the division of large numbers. Set P to an n-base Integer as the divisor, and Q to the number of divisor less than N (that is, the number of checksum code generation selected ):

P = a0n0 + a1n1 +... + aknk

Now we need to calculate the remainder rk of P ÷ Q, that is, R0 = P mod q, starting from rk:

Rk = aknk mod q
Rk-1 = (rkn + ak-1nk-1) mod q
...
R0 = (r1n + a0n0) mod q

Based on this recursive formula, it is easy to process the division of large numbers. To facilitate implementation, 216 = 65535 or 232 = 4294967295 can be used in the program. In this way, when calculating the remainder, you do not need to multiply the previous R by the hexadecimal notation. You only need to shift 16 or 32 bits to the left to maximize the use of the register and CPU features.

After obtaining the remainder, the next step is to convert the remainder into a verification code. If the verification code is set to C, the following conditions should be met:

(A0n0 + a1n1 +... + aknk + C) mod q = 0

Previously obtained:

(A0n0 + a1n1 +... + aknk) mod q = r

Obviously, C has more than one value, but the smallest positive value can be calculated using the following formula:

C = Q-(NR mod q)

The above formula is easy to understand and will not be repeated. So far, CRC code calculation is complete. There is another point to note here. We generally write programs and compile the machine environment (including the OJ system running environment) in X86 architecture, which means that the byte order is little-Endian, that is to say, all integer values in the memory are at the top and at the bottom. For example, if the 32-bit hexadecimal number is af045bh, the order in the memory should be:

5B 04 af 00

If we convert the string pointer to an int pointer for calculation, an error is returned. Each group of bytes (a group of integer variables) must be first reversed before computation.

 

Solution
Answer
# Include <algorithm> # include <iomanip> # include <iostream> # include <string> using namespace STD; int main (void) {typedef unsigned short word; char bits [1032]; // stores the input string cin. sync_with_stdio (false); // the input data volume is large. Disable synchronization to accelerate cout <setbase (16) <setiosflags (IOs: uppercase) <setfill ('0'); // cyclically processes each line of input string for (string line; Getline (CIN, line) & line [0]! = '#'; Cout <Endl) {word ngen = 34943, nlen = line. length (), * pbit = (word *) bits; // returns the string to a static array. X86 CPUs are in the little-Endian, reverse_copy (line. begin (), line. end (), BITs); // reverse to positive byte order * (word *) (& bits [nlen]) = 0; // clear all the digits after the end nlen = nlen/2 + (nlen % 2! = 0); // calculate the length of the int array long NREM = 0; // NREM indicates the remainder. // the remainder of the carry is accumulated after all the bits in the loop, generate CRC code for (INT I = nlen-1; I >=0; -- I) {NREM = (NREM <16) + pbit [I]) % ngen ;} if (NREM! = 0) {// if the remainder is not 0, a CRC code is required. For the algorithm, see NREM = ngen-(NREM <16) % ngen ;} // The following output CRC code unsigned char * pbyte = (unsigned char *) & NREM; cout <SETW (2) <(INT) pbyte [1] <''<SETW (2) <(INT) pbyte [0];} return 0 ;}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.