Understanding Cyclic Redundancy Code algorithm for beginners

后端 未结 3 1935
长情又很酷
长情又很酷 2021-01-20 10:14

at section 5.5 of the PNG Specification, it discusses this concept in the PNG file format called \"CRC\" or \"Cyclic Redundancy Code\". I\'ve never heard of it before, so I\

3条回答
  •  时光说笑
    2021-01-20 10:44

    The spec includes a link to example code:

    https://www.w3.org/TR/2003/REC-PNG-20031110/#D-CRCAppendix

    The spec has errors or is confusing.

    That should be "data from each byte is processed from the least significant bit(0) to the most significant bit bit(7).

    The CRC is a 33 term polynomial, where each term has a one bit coefficient, 0 or 1, with the 0 coefficients ignored when describing the polynomial.

    Think of the CRC as being held in a 32 bit register. The sequence is to xor a byte of data into the right most byte of the CRC register, bits 7 through 0 (which technically correspond to the polynomial coefficients of x^24 to x^31). Then the CRC is "cycled" to the right for 8 bits (via table lookup). Once all data bytes have gone through this cycle, based on the comment from Mark Adler, it's the CRC is appended to data most significant byte first, (CRC>>24)&0xff, (CRC>>16)&0xff, (CRC>>8)&0xff, (CRC)&0xff.

    The wiki article may help. For the example in the computation section, the dividend would be an array of data bytes with the bits of each byte reversed, the bits of the 33 bit polynomial would be non-reversed (0x104C11DB7). After doing the computation, the bits of the remainder would be reversed and appended to the data bytes.

    https://en.wikipedia.org/wiki/Cyclic_redundancy_check


    Mark Adler's answer includes a link to a good tutorial for a CRC. His answer also explains the x's used in a polynomial. It's just like a polynomial in algebra, except the coefficients can only be 0 or 1, and addition (or subtraction) is done using XOR.


    what is x

    From the wiki example:

    data     = 11010011101100 = x^13 + x^12 + x^10 + x^7 + x^6 + x^5 + x^3 + x^2
    divisor  =           1011 = x^3 + x + 1
    

    Three 0 bits are appended to the data, effectively multiplying it by x^3:

    dividend = 11010011101100000 = x^16 + x^15 + x^13 + x^10 + x^9 + x^8 + x^6 + x^5
    

    Then the crc = dividend % divisor, with coefficients restricted to 0 or 1.

    (x^16 + x^15 + x^13 + x^10 + x^9 + x^8 + x^6 + x^5) % (x^3 + x + 1) = x^2
    11010011101100000 % 1011 = 100
    

提交回复
热议问题