Calibration and calculation principle __ Binary

Source: Internet
Author: User
check and train of thought

First of all, IP, ICMP, UDP and TCP packet headers have a check and field, size is 16bit, the algorithm is basically the same.

When sending data, in order to compute the packet's test and. The following steps should be followed:

1, the Calibration and field set to 0

2, the need to verify the data as a 16-digit unit of the number composition, in turn, binary inverse code summation;

3, put the resulting results into the checksum field

When receiving data, the test and the relative simplicity of the calculation packet are as follows:

1, the first as a 16-digit unit of the number composition, followed by binary inverse code summation, including the checksum field,

2, check the calculated results of the checksum is 0;

3, if equal to 0, the description is divisible, checksum correct. Otherwise, the checksum is wrong, and the protocol stack discards the packet.

Although the above four kinds of messages of the same checksum algorithm, but in the scope of the difference: IP checksum only 20 bytes of IP header, while ICMP checksum coverage of the entire packet (ICMP header +icmp data), UDP and TCP checksum not only covers the entire message, There are also 12 bytes of IP pseudo header, including source IP address (4 bytes), Destination IP address (4 bytes), Protocol (2 bytes), tcp/udp Baochang (2 bytes). In addition, UDP, TCP datagram length can be an odd number of sections, so in the calculation of checksums need to be added at the end of the padding byte 0 (padding byte is only to calculate the checksum, can not be transmitted). Calibration and Calculation methods:

For an unsigned number, first find its inverse code, and then from low to high, bitwise addition, the benefit is to high into 1 (and the General binary rule), if the highest bit has carry, then to the lowest bit into 1.

Features: On the binary reverse code cycle shift summation operation needs to be explained that the first to take back after the addition and first added after the reverse, the result is the same. compatibility and exchangeable

Using A,b,c,d,e,f to represent a 8-bit binary number (a byte), in the form of [A, B], a*256+b, then 16-bit checksums can be given in the following form

sum = [a,b]+ ' [c,d]+ ' [e,f];

wherein, + ' is represented by binary cyclic shift addition

Binding: [a,b]+ ' [c,d]+ ' [e,f] = [a,b]+ ' ([c,d]+ ' [e,f]]
exchangeable: [a,b]+ ' [c,d]+ ' [e,f] = [c,d]+ ' [a,b]+ ' [e,f] byte autonomy

[a,b]+ ' [c,d]+ ' [e,f] = [b,a]+ ' ([d,c]+ ' [f,e]]

Because if the highest bit has carry, then to the lowest bit into 1 of such characteristics, 15th to 0 digits, 7th bit to the 8th bit, so the whole sum result is the same. Parallel Computing

Some of the machine's word processing length is a multiple of 16, which can improve his calculation speed, because the combination of lines, then 32-bit machine can [a,b,c,d]+ ' ... Perform a 32 checksum. Why do I use binary inverse code to shift the addition?

We know that the computer has the original code, inverse code, complement, why use binary inverse code to calculate the checksum, rather than directly using the original code or complement it. binary Inverse code cyclic shift addition sum advantage

The system is not dependent on the big end. That is, whether you are the sender of the computer or the receiver to check the checksum, do not call htons or NTOHS, directly through the above algorithm can get the correct results. This problem you can take for example, by using the inverse code summation, the exchange of 16-digit byte order, the result is the same, but the byte order is also exchanged accordingly, and if the use of the original code or complement, the result may be different.

Calculate and verify the checksum is simpler, express. For Example:

For a string of 16 data: 0001F203F4F5F6F7

The normal order is to move the high 8-bit *256, moving 8 digits to the left, plus the lower 8 digits, the Exchange order, and vice versa

It is obvious that binary inverse code cyclic shift addition has nothing to do with byte order. Code:

#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> using namespace std;
    void Main (int argc, char *argv[]) {FILE *fp;
    Char ch;
    unsigned char Lowchar, Highchar;
    unsigned int count = 0, checksum = 0, byte = 0;


    unsigned long int sum = 0;
        Open File text if ((fp = fopen ("I:\\1.txt", "r") = = NULL) {printf ("File cannot be opened!");
        System ("pause");
    Return
    printf ("4-bit-sum\n");                        Reads the character while (1) {if (ch = fgetc (fp))!=eof) {count++; Starting from 1 count if (ch!= ') {//Convert a 16-character to an >= ' 0 ' && Amp
                Ch <= ' 9 ') {ch-= ' 0 ';
                else if (Ch >= ' a ' && ch <= ' F ') {ch = ch-' a ' +10; else if (ch >= ' A ';& ch <= ' F ') {ch = ch-' A ' + 10; //Calculate the cumulative value of 8 bytes if (count%2 = 1) {Highchar = ch <     < 4;    As high four bit} of a byte else {lowchar = ch & 0x0f; As a byte of low four byte = highchar|
                    lowchar;//makes up a byte//16-bit parallel computation if (count% 4 = 2)//high 8 bits sum with sum   
                    {sum = = byte << 8;
                    else if (count% 4 = 0)//low 8 bits sum sum {sum = byte;
                printf ("%04x-%8lx \ n", Byte, sum);
            } else {count--;
        } else {break; }//If 16-bit sum produces a carry, add the feed to the low if (s)Um >>) {checksum = ~ (Long (sum>>16) +long (SUM&AMP;0X0000FFFF));
    printf ("\ n-shifted sum:%x" (Long (sum>>16) +long (SUM&AMP;0X0000FFFF));
    printf ("\nchecksum1:%x", checksum);

    Avoid Rounding checksum = checksum&0x0000ffff;

    Output checksum printf ("\nchecksum:%x\n", checksum);
System ("pause"); }
Run Results

Reference Blog: Portal

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.