Code crc error

A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to digital data. Blocks of data entering these systems get a short check value attached, based on the remainder of a polynomial division of their contents. On retrieval, the calculation is repeated and, in the event the check values do not match, corrective action can be taken against data corruption. CRCs can be used for error correction (see bitfilters).[1]

A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital networks and storage devices to detect accidental changes to digital data. Blocks of data entering these systems get a short check value attached, based on the remainder of a polynomial division of their contents. On retrieval, the calculation is repeated and, in the event the check values do not match, corrective action can be taken against data corruption. CRCs can be used for error correction (see bitfilters).[1]

CRCs are so called because the check (data verification) value is a redundancy (it expands the message without adding information) and the algorithm is based on cyclic codes. CRCs are popular because they are simple to implement in binary hardware, easy to analyze mathematically, and particularly good at detecting common errors caused by noise in transmission channels. Because the check value has a fixed length, the function that generates it is occasionally used as a hash function.

Introduction[edit]

CRCs are based on the theory of cyclic error-correcting codes. The use of systematic cyclic codes, which encode messages by adding a fixed-length check value, for the purpose of error detection in communication networks, was first proposed by W. Wesley Peterson in 1961.[2]
Cyclic codes are not only simple to implement but have the benefit of being particularly well suited for the detection of burst errors: contiguous sequences of erroneous data symbols in messages. This is important because burst errors are common transmission errors in many communication channels, including magnetic and optical storage devices. Typically an n-bit CRC applied to a data block of arbitrary length will detect any single error burst not longer than n bits, and the fraction of all longer error bursts that it will detect is (1 − 2n).

Specification of a CRC code requires definition of a so-called generator polynomial. This polynomial becomes the divisor in a polynomial long division, which takes the message as the dividend and in which the quotient is discarded and the remainder becomes the result. The important caveat is that the polynomial coefficients are calculated according to the arithmetic of a finite field, so the addition operation can always be performed bitwise-parallel (there is no carry between digits).

In practice, all commonly used CRCs employ the Galois field, or more simply a finite field, of two elements, GF(2). The two elements are usually called 0 and 1, comfortably matching computer architecture.

A CRC is called an n-bit CRC when its check value is n bits long. For a given n, multiple CRCs are possible, each with a different polynomial. Such a polynomial has highest degree n, which means it has n + 1 terms. In other words, the polynomial has a length of n + 1; its encoding requires n + 1 bits. Note that most polynomial specifications either drop the MSB or LSB, since they are always 1. The CRC and associated polynomial typically have a name of the form CRC-n-XXX as in the table below.

The simplest error-detection system, the parity bit, is in fact a 1-bit CRC: it uses the generator polynomial x + 1 (two terms),[3] and has the name CRC-1.

Application[edit]

A CRC-enabled device calculates a short, fixed-length binary sequence, known as the check value or CRC, for each block of data to be sent or stored and appends it to the data, forming a codeword.

When a codeword is received or read, the device either compares its check value with one freshly calculated from the data block, or equivalently, performs a CRC on the whole codeword and compares the resulting check value with an expected residue constant.

If the CRC values do not match, then the block contains a data error.

The device may take corrective action, such as rereading the block or requesting that it be sent again. Otherwise, the data is assumed to be error-free (though, with some small probability, it may contain undetected errors; this is inherent in the nature of error-checking).[4]

Data integrity[edit]

CRCs are specifically designed to protect against common types of errors on communication channels, where they can provide quick and reasonable assurance of the integrity of messages delivered. However, they are not suitable for protecting against intentional alteration of data.

Firstly, as there is no authentication, an attacker can edit a message and recompute the CRC without the substitution being detected. When stored alongside the data, CRCs and cryptographic hash functions by themselves do not protect against intentional modification of data. Any application that requires protection against such attacks must use cryptographic authentication mechanisms, such as message authentication codes or digital signatures (which are commonly based on cryptographic hash functions).

Secondly, unlike cryptographic hash functions, CRC is an easily reversible function, which makes it unsuitable for use in digital signatures.[5]

Thirdly, CRC satisfies a relation similar to that of a linear function (or more accurately, an affine function):[6]

{displaystyle operatorname {CRC} (xoplus y)=operatorname {CRC} (x)oplus operatorname {CRC} (y)oplus c}

where c depends on the length of x and y. This can be also stated as follows, where x, y and z have the same length

{displaystyle operatorname {CRC} (xoplus yoplus z)=operatorname {CRC} (x)oplus operatorname {CRC} (y)oplus operatorname {CRC} (z);}

as a result, even if the CRC is encrypted with a stream cipher that uses XOR as its combining operation (or mode of block cipher which effectively turns it into a stream cipher, such as OFB or CFB), both the message and the associated CRC can be manipulated without knowledge of the encryption key; this was one of the well-known design flaws of the Wired Equivalent Privacy (WEP) protocol.[7]

Computation[edit]

To compute an n-bit binary CRC, line the bits representing the input in a row, and position the (n + 1)-bit pattern representing the CRC’s divisor (called a «polynomial») underneath the left end of the row.

In this example, we shall encode 14 bits of message with a 3-bit CRC, with a polynomial x3 + x + 1. The polynomial is written in binary as the coefficients; a 3rd-degree polynomial has 4 coefficients (1x3 + 0x2 + 1x + 1). In this case, the coefficients are 1, 0, 1 and 1. The result of the calculation is 3 bits long, which is why it is called a 3-bit CRC. However, you need 4 bits to explicitly state the polynomial.

Start with the message to be encoded:

11010011101100

This is first padded with zeros corresponding to the bit length n of the CRC. This is done so that the resulting code word is in systematic form. Here is the first calculation for computing a 3-bit CRC:

11010011101100 000 <--- input right padded by 3 bits
1011               <--- divisor (4 bits) = x³ + x + 1
------------------
01100011101100 000 <--- result

The algorithm acts on the bits directly above the divisor in each step. The result for that iteration is the bitwise XOR of the polynomial divisor with the bits above it. The bits not above the divisor are simply copied directly below for that step. The divisor is then shifted right to align with the highest remaining 1 bit in the input, and the process is repeated until the divisor reaches the right-hand end of the input row. Here is the entire calculation:

11010011101100 000 <--- input right padded by 3 bits
1011               <--- divisor
01100011101100 000 <--- result (note the first four bits are the XOR with the divisor beneath, the rest of the bits are unchanged)
 1011              <--- divisor ...
00111011101100 000
  1011
00010111101100 000
   1011
00000001101100 000 <--- note that the divisor moves over to align with the next 1 in the dividend (since quotient for that step was zero)
       1011             (in other words, it doesn't necessarily move one bit per iteration)
00000000110100 000
        1011
00000000011000 000
         1011
00000000001110 000
          1011
00000000000101 000
           101 1
-----------------
00000000000000 100 <--- remainder (3 bits).  Division algorithm stops here as dividend is equal to zero.

Since the leftmost divisor bit zeroed every input bit it touched, when this process ends the only bits in the input row that can be nonzero are the n bits at the right-hand end of the row. These n bits are the remainder of the division step, and will also be the value of the CRC function (unless the chosen CRC specification calls for some postprocessing).

The validity of a received message can easily be verified by performing the above calculation again, this time with the check value added instead of zeroes. The remainder should equal zero if there are no detectable errors.

11010011101100 100 <--- input with check value
1011               <--- divisor
01100011101100 100 <--- result
 1011              <--- divisor ...
00111011101100 100

......

00000000001110 100
          1011
00000000000101 100
           101 1
------------------
00000000000000 000 <--- remainder

The following Python code outlines a function which will return the initial CRC remainder for a chosen input and polynomial, with either 1 or 0 as the initial padding. Note that this code works with string inputs rather than raw numbers:

def crc_remainder(input_bitstring, polynomial_bitstring, initial_filler):
    """Calculate the CRC remainder of a string of bits using a chosen polynomial.
    initial_filler should be '1' or '0'.
    """
    polynomial_bitstring = polynomial_bitstring.lstrip('0')
    len_input = len(input_bitstring)
    initial_padding = (len(polynomial_bitstring) - 1) * initial_filler
    input_padded_array = list(input_bitstring + initial_padding)
    while '1' in input_padded_array[:len_input]:
        cur_shift = input_padded_array.index('1')
        for i in range(len(polynomial_bitstring)):
            input_padded_array[cur_shift + i] 
            = str(int(polynomial_bitstring[i] != input_padded_array[cur_shift + i]))
    return ''.join(input_padded_array)[len_input:]

def crc_check(input_bitstring, polynomial_bitstring, check_value):
    """Calculate the CRC check of a string of bits using a chosen polynomial."""
    polynomial_bitstring = polynomial_bitstring.lstrip('0')
    len_input = len(input_bitstring)
    initial_padding = check_value
    input_padded_array = list(input_bitstring + initial_padding)
    while '1' in input_padded_array[:len_input]:
        cur_shift = input_padded_array.index('1')
        for i in range(len(polynomial_bitstring)):
            input_padded_array[cur_shift + i] 
            = str(int(polynomial_bitstring[i] != input_padded_array[cur_shift + i]))
    return ('1' not in ''.join(input_padded_array)[len_input:])
>>> crc_remainder('11010011101100', '1011', '0')
'100'
>>> crc_check('11010011101100', '1011', '100')
True

CRC-32 algorithm[edit]

This is a practical algorithm for the CRC-32 variant of CRC.[8] The CRCTable is a memoization of a calculation that would have to be repeated for each byte of the message (Computation of cyclic redundancy checks § Multi-bit computation).

Function CRC32
   Input:
      data:  Bytes     // Array of bytes
   Output:
      crc32: UInt32    // 32-bit unsigned CRC-32 value
// Initialize CRC-32 to starting value crc32 ← 0xFFFFFFFF
for each byte in data do nLookupIndex ← (crc32 xor byte) and 0xFF crc32 ← (crc32 shr 8) xor CRCTable[nLookupIndex] // CRCTable is an array of 256 32-bit constants
// Finalize the CRC-32 value by inverting all the bits crc32 ← crc32 xor 0xFFFFFFFF return crc32

In C, the algorithm looks as such:

#include <inttypes.h> // uint32_t, uint8_t

uint32_t CRC32(const uint8_t data[], size_t data_length) {
	uint32_t crc32 = 0xFFFFFFFFu;
	
	for (size_t i = 0; i < data_length; i++) {
		const uint32_t lookupIndex = (crc32 ^ data[i]) & 0xff;
		crc32 = (crc32 >> 8) ^ CRCTable[lookupIndex];  // CRCTable is an array of 256 32-bit constants
	}
	
	// Finalize the CRC-32 value by inverting all the bits
	crc32 ^= 0xFFFFFFFFu;
	return crc32;
}

Mathematics[edit]

Mathematical analysis of this division-like process reveals how to select a divisor that guarantees good error-detection properties. In this analysis, the digits of the bit strings are taken as the coefficients of a polynomial in some variable x—coefficients that are elements of the finite field GF(2) (the integers modulo 2, i.e. either a zero or a one), instead of more familiar numbers. The set of binary polynomials is a mathematical ring.

Designing polynomials[edit]

The selection of the generator polynomial is the most important part of implementing the CRC algorithm. The polynomial must be chosen to maximize the error-detecting capabilities while minimizing overall collision probabilities.

The most important attribute of the polynomial is its length (largest degree(exponent) +1 of any one term in the polynomial), because of its direct influence on the length of the computed check value.

The most commonly used polynomial lengths are 9 bits (CRC-8), 17 bits (CRC-16), 33 bits (CRC-32), and 65 bits (CRC-64).[3]

A CRC is called an n-bit CRC when its check value is n-bits. For a given n, multiple CRCs are possible, each with a different polynomial. Such a polynomial has highest degree n, and hence n + 1 terms (the polynomial has a length of n + 1). The remainder has length n. The CRC has a name of the form CRC-n-XXX.

The design of the CRC polynomial depends on the maximum total length of the block to be protected (data + CRC bits), the desired error protection features, and the type of resources for implementing the CRC, as well as the desired performance. A common misconception is that the «best» CRC polynomials are derived from either irreducible polynomials or irreducible polynomials times the factor 1 + x, which adds to the code the ability to detect all errors affecting an odd number of bits.[9] In reality, all the factors described above should enter into the selection of the polynomial and may lead to a reducible polynomial. However, choosing a reducible polynomial will result in a certain proportion of missed errors, due to the quotient ring having zero divisors.

The advantage of choosing a primitive polynomial as the generator for a CRC code is that the resulting code has maximal total block length in the sense that all 1-bit errors within that block length have different remainders (also called syndromes) and therefore, since the remainder is a linear function of the block, the code can detect all 2-bit errors within that block length. If r is the degree of the primitive generator polynomial, then the maximal total block length is 2^{r}-1, and the associated code is able to detect any single-bit or double-bit errors.[10] We can improve this situation. If we use the generator polynomial g(x)=p(x)(1+x), where p is a primitive polynomial of degree r-1, then the maximal total block length is 2^{r-1}-1, and the code is able to detect single, double, triple and any odd number of errors.

A polynomial g(x) that admits other factorizations may be chosen then so as to balance the maximal total blocklength with a desired error detection power. The BCH codes are a powerful class of such polynomials. They subsume the two examples above. Regardless of the reducibility properties of a generator polynomial of degree r, if it includes the «+1» term, the code will be able to detect error patterns that are confined to a window of r contiguous bits. These patterns are called «error bursts».

Specification[edit]

The concept of the CRC as an error-detecting code gets complicated when an implementer or standards committee uses it to design a practical system. Here are some of the complications:

  • Sometimes an implementation prefixes a fixed bit pattern to the bitstream to be checked. This is useful when clocking errors might insert 0-bits in front of a message, an alteration that would otherwise leave the check value unchanged.
  • Usually, but not always, an implementation appends n 0-bits (n being the size of the CRC) to the bitstream to be checked before the polynomial division occurs. Such appending is explicitly demonstrated in the Computation of CRC article. This has the convenience that the remainder of the original bitstream with the check value appended is exactly zero, so the CRC can be checked simply by performing the polynomial division on the received bitstream and comparing the remainder with zero. Due to the associative and commutative properties of the exclusive-or operation, practical table driven implementations can obtain a result numerically equivalent to zero-appending without explicitly appending any zeroes, by using an equivalent,[9] faster algorithm that combines the message bitstream with the stream being shifted out of the CRC register.
  • Sometimes an implementation exclusive-ORs a fixed bit pattern into the remainder of the polynomial division.
  • Bit order: Some schemes view the low-order bit of each byte as «first», which then during polynomial division means «leftmost», which is contrary to our customary understanding of «low-order». This convention makes sense when serial-port transmissions are CRC-checked in hardware, because some widespread serial-port transmission conventions transmit bytes least-significant bit first.
  • Byte order: With multi-byte CRCs, there can be confusion over whether the byte transmitted first (or stored in the lowest-addressed byte of memory) is the least-significant byte (LSB) or the most-significant byte (MSB). For example, some 16-bit CRC schemes swap the bytes of the check value.
  • Omission of the high-order bit of the divisor polynomial: Since the high-order bit is always 1, and since an n-bit CRC must be defined by an (n + 1)-bit divisor which overflows an n-bit register, some writers assume that it is unnecessary to mention the divisor’s high-order bit.
  • Omission of the low-order bit of the divisor polynomial: Since the low-order bit is always 1, authors such as Philip Koopman represent polynomials with their high-order bit intact, but without the low-order bit (the x^{0} or 1 term). This convention encodes the polynomial complete with its degree in one integer.

These complications mean that there are three common ways to express a polynomial as an integer: the first two, which are mirror images in binary, are the constants found in code; the third is the number found in Koopman’s papers. In each case, one term is omitted. So the polynomial x^{4}+x+1 may be transcribed as:

In the table below they are shown as:

Examples of CRC representations

Name Normal Reversed Reversed reciprocal
CRC-4 0x3 0xC 0x9

Obfuscation[edit]

CRCs in proprietary protocols might be obfuscated by using a non-trivial initial value and a final XOR, but these techniques do not add cryptographic strength to the algorithm and can be reverse engineered using straightforward methods.[11]

Standards and common use[edit]

Numerous varieties of cyclic redundancy checks have been incorporated into technical standards. By no means does one algorithm, or one of each degree, suit every purpose; Koopman and Chakravarty recommend selecting a polynomial according to the application requirements and the expected distribution of message lengths.[12] The number of distinct CRCs in use has confused developers, a situation which authors have sought to address.[9] There are three polynomials reported for CRC-12,[12] twenty-two conflicting definitions of CRC-16, and seven of CRC-32.[13]

The polynomials commonly applied are not the most efficient ones possible. Since 1993, Koopman, Castagnoli and others have surveyed the space of polynomials between 3 and 64 bits in size,[12][14][15][16] finding examples that have much better performance (in terms of Hamming distance for a given message size) than the polynomials of earlier protocols, and publishing the best of these with the aim of improving the error detection capacity of future standards.[15] In particular, iSCSI and SCTP have adopted one of the findings of this research, the CRC-32C (Castagnoli) polynomial.

The design of the 32-bit polynomial most commonly used by standards bodies, CRC-32-IEEE, was the result of a joint effort for the Rome Laboratory and the Air Force Electronic Systems Division by Joseph Hammond, James Brown and Shyan-Shiang Liu of the Georgia Institute of Technology and Kenneth Brayer of the Mitre Corporation. The earliest known appearances of the 32-bit polynomial were in their 1975 publications: Technical Report 2956 by Brayer for Mitre, published in January and released for public dissemination through DTIC in August,[17] and Hammond, Brown and Liu’s report for the Rome Laboratory, published in May.[18] Both reports contained contributions from the other team. During December 1975, Brayer and Hammond presented their work in a paper at the IEEE National Telecommunications Conference: the IEEE CRC-32 polynomial is the generating polynomial of a Hamming code and was selected for its error detection performance.[19] Even so, the Castagnoli CRC-32C polynomial used in iSCSI or SCTP matches its performance on messages from 58 bits to 131 kbits, and outperforms it in several size ranges including the two most common sizes of Internet packet.[15] The ITU-T G.hn standard also uses CRC-32C to detect errors in the payload (although it uses CRC-16-CCITT for PHY headers).

CRC-32C computation is implemented in hardware as an operation (CRC32) of SSE4.2 instruction set, first introduced in Intel processors’ Nehalem microarchitecture. ARM AArch64 architecture also provides hardware acceleration for both CRC-32 and CRC-32C operations.

Polynomial representations of cyclic redundancy checks[edit]

The table below lists only the polynomials of the various algorithms in use. Variations of a particular protocol can impose pre-inversion, post-inversion and reversed bit ordering as described above. For example, the CRC32 used in Gzip and Bzip2 use the same polynomial, but Gzip employs reversed bit ordering, while Bzip2 does not.[13]
Note that even parity polynomials in GF(2) with degree greater than 1 are never primitive. Even parity polynomial marked as primitive in this table represent a primitive polynomial multiplied by {displaystyle left(x+1right)}. The most significant bit of a polynomial is always 1, and is not shown in the hex representations.

Name Uses Polynomial representations Parity[20] Primitive[21] Maximum bits of payload by Hamming distance[22][15][21]
Normal Reversed Reciprocal Reversed reciprocal ≥ 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2[23]
CRC-1 most hardware; also known as parity bit 0x1 0x1 0x1 0x1 even
x+1
CRC-3-GSM mobile networks[24] 0x3 0x6 0x5 0x5 odd yes [25] 4
x^{3}+x+1
CRC-4-ITU ITU-T G.704, p. 12 0x3 0xC 0x9 0x9 odd
x^{4}+x+1
CRC-5-EPC Gen 2 RFID[26] 0x09 0x12 0x05 0x14 odd
x^{5}+x^{3}+1
CRC-5-ITU ITU-T G.704, p. 9 0x15 0x15 0x0B 0x1A even
x^{5}+x^{4}+x^{2}+1
CRC-5-USB USB token packets 0x05 0x14 0x09 0x12 odd
x^{5}+x^{2}+1
CRC-6-CDMA2000-A mobile networks[27] 0x27 0x39 0x33 0x33 odd
CRC-6-CDMA2000-B mobile networks[27] 0x07 0x38 0x31 0x23 even
CRC-6-DARC Data Radio Channel[28] 0x19 0x26 0x0D 0x2C even
CRC-6-GSM mobile networks[24] 0x2F 0x3D 0x3B 0x37 even yes [29] 1 1 25 25
{displaystyle x^{6}+x^{5}+x^{3}+x^{2}+x+1}
CRC-6-ITU ITU-T G.704, p. 3 0x03 0x30 0x21 0x21 odd
x^{6}+x+1
CRC-7 telecom systems, ITU-T G.707, ITU-T G.832, MMC, SD 0x09 0x48 0x11 0x44 odd
x^{7}+x^{3}+1
CRC-7-MVB Train Communication Network, IEC 60870-5[30] 0x65 0x53 0x27 0x72 odd
CRC-8 DVB-S2[31] 0xD5 0xAB 0x57 0xEA[12] even no [32] 2 2 85 85
x^{8}+x^{7}+x^{6}+x^{4}+x^{2}+1
CRC-8-AUTOSAR automotive integration,[33] OpenSafety[34] 0x2F 0xF4 0xE9 0x97[12] even yes [32] 3 3 119 119
{displaystyle x^{8}+x^{5}+x^{3}+x^{2}+x+1}
CRC-8-Bluetooth wireless connectivity[35] 0xA7 0xE5 0xCB 0xD3 even
{displaystyle x^{8}+x^{7}+x^{5}+x^{2}+x+1}
CRC-8-CCITT ITU-T I.432.1 (02/99); ATM HEC, ISDN HEC and cell delineation, SMBus PEC 0x07 0xE0 0xC1 0x83 even
x^{8}+x^{2}+x+1
CRC-8-Dallas/Maxim 1-Wire bus[36] 0x31 0x8C 0x19 0x98 even
x^{8}+x^{5}+x^{4}+1
CRC-8-DARC Data Radio Channel[28] 0x39 0x9C 0x39 0x9C odd
{displaystyle x^{8}+x^{5}+x^{4}+x^{3}+1}
CRC-8-GSM-B mobile networks[24] 0x49 0x92 0x25 0xA4 even
{displaystyle x^{8}+x^{6}+x^{3}+1}
CRC-8-SAE J1850 AES3; OBD 0x1D 0xB8 0x71 0x8E odd
x^{8}+x^{4}+x^{3}+x^{2}+1
CRC-8-WCDMA mobile networks[27][37] 0x9B 0xD9 0xB3 0xCD[12] even
x^{8}+x^{7}+x^{4}+x^{3}+x+1
CRC-10 ATM; ITU-T I.610 0x233 0x331 0x263 0x319 even
x^{{10}}+x^{9}+x^{5}+x^{4}+x+1
CRC-10-CDMA2000 mobile networks[27] 0x3D9 0x26F 0x0DF 0x3EC even
CRC-10-GSM mobile networks[24] 0x175 0x2BA 0x175 0x2BA odd
CRC-11 FlexRay[38] 0x385 0x50E 0x21D 0x5C2 even
x^{{11}}+x^{9}+x^{8}+x^{7}+x^{2}+1
CRC-12 telecom systems[39][40] 0x80F 0xF01 0xE03 0xC07[12] even
x^{{12}}+x^{{11}}+x^{3}+x^{2}+x+1
CRC-12-CDMA2000 mobile networks[27] 0xF13 0xC8F 0x91F 0xF89 even
CRC-12-GSM mobile networks[24] 0xD31 0x8CB 0x197 0xE98 odd
CRC-13-BBC Time signal, Radio teleswitch[41][42] 0x1CF5 0x15E7 0x0BCF 0x1E7A even
x^{{13}}+x^{{12}}+x^{{11}}+x^{{10}}+x^{7}+x^{6}+x^{5}+x^{4}+x^{2}+1
CRC-14-DARC Data Radio Channel[28] 0x0805 0x2804 0x1009 0x2402 even
CRC-14-GSM mobile networks[24] 0x202D 0x2D01 0x1A03 0x3016 even
CRC-15-CAN 0xC599[43][44] 0x4CD1 0x19A3 0x62CC even
x^{{15}}+x^{{14}}+x^{{10}}+x^{8}+x^{7}+x^{4}+x^{3}+1
CRC-15-MPT1327 [45] 0x6815 0x540B 0x2817 0x740A odd
CRC-16-Chakravarty Optimal for payloads ≤64 bits[30] 0x2F15 0xA8F4 0x51E9 0x978A odd
CRC-16-ARINC ACARS applications[46] 0xA02B 0xD405 0xA80B 0xD015 odd
CRC-16-CCITT X.25, V.41, HDLC FCS, XMODEM, Bluetooth, PACTOR, SD, DigRF, many others; known as CRC-CCITT 0x1021 0x8408 0x811 0x8810[12] even
x^{16} + x^{12} + x^5 + 1
CRC-16-CDMA2000 mobile networks[27] 0xC867 0xE613 0xCC27 0xE433 odd
CRC-16-DECT cordless telephones[47] 0x0589 0x91A0 0x2341 0x82C4 even
x^{{16}}+x^{{10}}+x^{8}+x^{7}+x^{3}+1
CRC-16-T10-DIF SCSI DIF 0x8BB7[48] 0xEDD1 0xDBA3 0xC5DB odd
x^{{16}}+x^{{15}}+x^{{11}}+x^{{9}}+x^{8}+x^{7}+x^{5}+x^{4}+x^{2}+x+1
CRC-16-DNP DNP, IEC 870, M-Bus 0x3D65 0xA6BC 0x4D79 0x9EB2 even
x^{{16}}+x^{{13}}+x^{{12}}+x^{{11}}+x^{{10}}+x^{8}+x^{6}+x^{5}+x^{2}+1
CRC-16-IBM Bisync, Modbus, USB, ANSI X3.28, SIA DC-07, many others; also known as CRC-16 and CRC-16-ANSI 0x8005 0xA001 0x4003 0xC002 even
x^{16} + x^{15} + x^2 + 1
CRC-16-OpenSafety-A safety fieldbus[34] 0x5935 0xAC9A 0x5935 0xAC9A[12] odd
CRC-16-OpenSafety-B safety fieldbus[34] 0x755B 0xDAAE 0xB55D 0xBAAD[12] odd
CRC-16-Profibus fieldbus networks[49] 0x1DCF 0xF3B8 0xE771 0x8EE7 odd
Fletcher-16 Used in Adler-32 A & B Checksums Often confused to be a CRC, but actually a checksum; see Fletcher’s checksum
CRC-17-CAN CAN FD[50] 0x1685B 0x1B42D 0x1685B 0x1B42D even
CRC-21-CAN CAN FD[50] 0x102899 0x132281 0x064503 0x18144C even
CRC-24 FlexRay[38] 0x5D6DCB 0xD3B6BA 0xA76D75 0xAEB6E5 even
x^{{24}}+x^{{22}}+x^{{20}}+x^{{19}}+x^{{18}}+x^{{16}}+x^{{14}}+x^{{13}}+x^{{11}}+x^{{10}}+x^{8}+x^{7}+x^{6}+x^{3}+x+1
CRC-24-Radix-64 OpenPGP, RTCM104v3 0x864CFB 0xDF3261 0xBE64C3 0xC3267D even
x^{{24}}+x^{{23}}+x^{{18}}+x^{{17}}+x^{{14}}+x^{{11}}+x^{{10}}+x^{7}+x^{6}+x^{5}+x^{4}+x^{3}+x+1
CRC-24-WCDMA Used in OS-9 RTOS. Residue = 0x800FE3.[51] 0x800063 0xC60001 0x8C0003 0xC00031 even yes[52] 4 4 8388583 8388583
{displaystyle x^{24}+x^{23}+x^{6}+x^{5}+x+1}
CRC-30 CDMA 0x2030B9C7 0x38E74301 0x31CE8603 0x30185CE3 even
x^{{30}}+x^{{29}}+x^{{21}}+x^{{20}}+x^{{15}}+x^{{13}}+x^{{12}}+x^{{11}}+x^{{8}}+x^{{7}}+x^{{6}}+x^{{2}}+x+1
CRC-32 ISO 3309 (HDLC), ANSI X3.66 (ADCCP), FIPS PUB 71, FED-STD-1003, ITU-T V.42, ISO/IEC/IEEE 802-3 (Ethernet), SATA, MPEG-2, PKZIP, Gzip, Bzip2, POSIX cksum,[53] PNG,[54] ZMODEM, many others 0x04C11DB7 0xEDB88320 0xDB710641 0x82608EDB[15] odd yes 10 12 21 34 57 91 171 268 2974 91607 4294967263
x^{{32}}+x^{{26}}+x^{{23}}+x^{{22}}+x^{{16}}+x^{{12}}+x^{{11}}+x^{{10}}+x^{8}+x^{7}+x^{5}+x^{4}+x^{2}+x+1
CRC-32C (Castagnoli) iSCSI, SCTP, G.hn payload, SSE4.2, Btrfs, ext4, Ceph 0x1EDC6F41 0x82F63B78 0x05EC76F1 0x8F6E37A0[15] even yes 6 8 20 47 177 5243 2147483615
x^{{32}}+x^{{28}}+x^{{27}}+x^{{26}}+x^{{25}}+x^{{23}}+x^{{22}}+x^{{20}}+x^{{19}}+x^{{18}}+x^{{14}}+x^{{13}}+x^{{11}}+x^{{10}}+x^{9}+x^{8}+x^{6}+1
CRC-32K (Koopman {1,3,28}) Excellent at Ethernet frame length, poor performance with long files 0x741B8CD7 0xEB31D82E 0xD663B05D 0xBA0DC66B[15] even no 2 4 16 18 152 16360 114663
x^{{32}}+x^{{30}}+x^{{29}}+x^{{28}}+x^{{26}}+x^{{20}}+x^{{19}}+x^{{17}}+x^{{16}}+x^{{15}}+x^{{11}}+x^{{10}}+x^{{7}}+x^{{6}}+x^{{4}}+x^{{2}}+x+1
CRC-32K2 (Koopman {1,1,30}) Excellent at Ethernet frame length, poor performance with long files 0x32583499 0x992C1A4C 0x32583499 0x992C1A4C[15] even no 3 16 26 134 32738 65506
CRC-32Q aviation; AIXM[55] 0x814141AB 0xD5828281 0xAB050503 0xC0A0A0D5 even
x^{{32}}+x^{{31}}+x^{{24}}+x^{{22}}+x^{{16}}+x^{{14}}+x^{{8}}+x^{{7}}+x^{{5}}+x^{{3}}+x+1
Adler-32 Often confused to be a CRC, but actually a checksum; see Adler-32
CRC-40-GSM GSM control channel[56][57][58] 0x0004820009 0x9000412000 0x2000824001 0x8002410004 even
{displaystyle x^{40}+x^{26}+x^{23}+x^{17}+x^{3}+1=(x^{23}+1)(x^{17}+x^{3}+1)}
CRC-64-ECMA ECMA-182 p. 51, XZ Utils 0x42F0E1EBA9EA3693 0xC96C5795D7870F42 0x92D8AF2BAF0E1E85 0xA17870F5D4F51B49 even
x^{{64}}+x^{{62}}+x^{{57}}+x^{{55}}+x^{{54}}+x^{{53}}+x^{{52}}+x^{{47}}+x^{{46}}+x^{{45}}+x^{{40}}+x^{{39}}+x^{{38}}+x^{{37}}+x^{{35}}+x^{{33}}+ x^{{32}}+x^{{31}}+x^{{29}}+x^{{27}}+x^{{24}}+x^{{23}}+x^{{22}}+x^{{21}}+x^{{19}}+x^{{17}}+x^{{13}}+x^{{12}}+x^{{10}}+x^{9}+x^{7}+x^{4}+x+1
CRC-64-ISO ISO 3309 (HDLC), Swiss-Prot/TrEMBL; considered weak for hashing[59] 0x000000000000001B 0xD800000000000000 0xB000000000000001 0x800000000000000D odd
x^{{64}}+x^{4}+x^{3}+x+1

Implementations[edit]

  • Implementation of CRC32 in GNU Radio up to 3.6.1 (ca. 2012)
  • C class code for CRC checksum calculation with many different CRCs to choose from

CRC catalogues[edit]

  • Catalogue of parametrised CRC algorithms
  • CRC Polynomial Zoo

See also[edit]

  • Mathematics of cyclic redundancy checks
  • Computation of cyclic redundancy checks
  • List of hash functions
  • List of checksum algorithms
  • Information security
  • Simple file verification
  • LRC

References[edit]

  1. ^ «An Algorithm for Error Correcting Cyclic Redundance Checks». drdobbs.com. Archived from the original on 20 July 2017. Retrieved 28 June 2017.
  2. ^ Peterson, W. W.; Brown, D. T. (January 1961). «Cyclic Codes for Error Detection». Proceedings of the IRE. 49 (1): 228–235. doi:10.1109/JRPROC.1961.287814. S2CID 51666741.
  3. ^ a b Ergen, Mustafa (21 January 2008). «2.3.3 Error Detection Coding». Mobile Broadband. Springer. pp. 29–30. doi:10.1007/978-0-387-68192-4_2. ISBN 978-0-387-68192-4.
  4. ^ Ritter, Terry (February 1986). «The Great CRC Mystery». Dr. Dobb’s Journal. 11 (2): 26–34, 76–83. Archived from the original on 16 April 2009. Retrieved 21 May 2009.
  5. ^ Stigge, Martin; Plötz, Henryk; Müller, Wolf; Redlich, Jens-Peter (May 2006). «Reversing CRC – Theory and Practice» (PDF). Humboldt University Berlin. p. 17. SAR-PR-2006-05. Archived from the original (PDF) on 19 July 2011. Retrieved 4 February 2011. The presented methods offer a very easy and efficient way to modify your data so that it will compute to a CRC you want or at least know in advance.
  6. ^ «algorithm design — Why is CRC said to be linear?». Cryptography Stack Exchange. Retrieved 5 May 2019.
  7. ^ Cam-Winget, Nancy; Housley, Russ; Wagner, David; Walker, Jesse (May 2003). «Security Flaws in 802.11 Data Link Protocols» (PDF). Communications of the ACM. 46 (5): 35–39. CiteSeerX 10.1.1.14.8775. doi:10.1145/769800.769823. S2CID 3132937. Archived (PDF) from the original on 26 May 2013. Retrieved 1 November 2017.
  8. ^ «[MS-ABS]: 32-Bit CRC Algorithm». msdn.microsoft.com. Archived from the original on 7 November 2017. Retrieved 4 November 2017.
  9. ^ a b c Williams, Ross N. (24 September 1996). «A Painless Guide to CRC Error Detection Algorithms V3.0». Archived from the original on 2 April 2018. Retrieved 23 May 2019.
  10. ^ Press, WH; Teukolsky, SA; Vetterling, WT; Flannery, BP (2007). «Section 22.4 Cyclic Redundancy and Other Checksums». Numerical Recipes: The Art of Scientific Computing (3rd ed.). Cambridge University Press. ISBN 978-0-521-88068-8. Archived from the original on 11 August 2011. Retrieved 18 August 2011.
  11. ^ Ewing, Gregory C. (March 2010). «Reverse-Engineering a CRC Algorithm». Christchurch: University of Canterbury. Archived from the original on 7 August 2011. Retrieved 26 July 2011.
  12. ^ a b c d e f g h i j Koopman, Philip; Chakravarty, Tridib (June 2004). Cyclic Redundancy Code (CRC) Polynomial Selection For Embedded Networks (PDF). The International Conference on Dependable Systems and Networks. pp. 145–154. CiteSeerX 10.1.1.648.9080. doi:10.1109/DSN.2004.1311885. ISBN 978-0-7695-2052-0. S2CID 793862. Archived (PDF) from the original on 11 September 2011. Retrieved 14 January 2011.
  13. ^ a b Cook, Greg (15 August 2020). «Catalogue of parametrised CRC algorithms». Archived from the original on 1 August 2020. Retrieved 18 September 2020.
  14. ^ Castagnoli, G.; Bräuer, S.; Herrmann, M. (June 1993). «Optimization of Cyclic Redundancy-Check Codes with 24 and 32 Parity Bits». IEEE Transactions on Communications. 41 (6): 883–892. doi:10.1109/26.231911.
  15. ^ a b c d e f g h Koopman, Philip (July 2002). «32-Bit Cyclic Redundancy Codes for Internet Applications». Proceedings International Conference on Dependable Systems and Networks (PDF). The International Conference on Dependable Systems and Networks. pp. 459–468. CiteSeerX 10.1.1.11.8323. doi:10.1109/DSN.2002.1028931. ISBN 978-0-7695-1597-7. S2CID 14775606. Archived (PDF) from the original on 16 September 2012. Retrieved 14 January 2011.
  16. ^ Koopman, Philip (21 January 2016). «Best CRC Polynomials». Carnegie Mellon University. Archived from the original on 20 January 2016. Retrieved 26 January 2016.
  17. ^ Brayer, Kenneth (August 1975). Evaluation of 32 Degree Polynomials in Error Detection on the SATIN IV Autovon Error Patterns (Report). National Technical Information Service. ADA014825. Archived from the original on 31 December 2021. Retrieved 31 December 2021.
  18. ^ Hammond, Joseph L. Jr.; Brown, James E.; Liu, Shyan-Shiang (1975). «Development of a Transmission Error Model and an Error Control Model». NASA Sti/Recon Technical Report N (published May 1975). 76: 15344. Bibcode:1975STIN…7615344H. ADA013939. Archived from the original on 31 December 2021. Retrieved 31 December 2021.
  19. ^ Brayer, Kenneth; Hammond, Joseph L. Jr. (December 1975). Evaluation of error detection polynomial performance on the AUTOVON channel. NTC 75 : National Telecommunications Conference, December 1-3, 1975, New Orleans, Louisiana. Vol. 1. Institute of Electrical and Electronics Engineers. pp. 8-21–5. Bibcode:1975ntc…..1….8B. OCLC 32688603. 75 CH 1015-7 CSCB.
  20. ^ CRCs with even parity detect any odd number of bit errors, at the expense of lower hamming distance for long payloads. Note that parity is computed over the entire generator polynomial, including implied 1 at the beginning or the end. For example, the full representation of CRC-1 is 0x3, which has two 1 bits. Thus, its parity is even.
  21. ^ a b «32 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 19 March 2018. Retrieved 5 November 2017.
  22. ^ Payload means length exclusive of CRC field. A Hamming distance of d means that d − 1 bit errors can be detected and ⌊(d − 1)/2⌋ bit errors can be corrected
  23. ^ is always achieved for arbitrarily long messages
  24. ^ a b c d e f ETSI TS 100 909 (PDF). V8.9.0. Sophia Antipolis, France: European Telecommunications Standards Institute. January 2005. Archived (PDF) from the original on 17 April 2018. Retrieved 21 October 2016.
  25. ^ «3 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
  26. ^ Class-1 Generation-2 UHF RFID Protocol (PDF). 1.2.0. EPCglobal. 23 October 2008. p. 35. Archived (PDF) from the original on 19 March 2012. Retrieved 4 July 2012. (Table 6.12)
  27. ^ a b c d e f Physical layer standard for cdma2000 spread spectrum systems (PDF). Revision D version 2.0. 3rd Generation Partnership Project 2. October 2005. pp. 2–89–2–92. Archived from the original (PDF) on 16 November 2013. Retrieved 14 October 2013.
  28. ^ a b c «11. Error correction strategy». ETSI EN 300 751 (PDF). V1.2.1. Sophia Antipolis, France: European Telecommunications Standards Institute. January 2003. pp. 67–8. Archived (PDF) from the original on 28 December 2015. Retrieved 26 January 2016.
  29. ^ «6 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
  30. ^ a b Chakravarty, Tridib (December 2001). Performance of Cyclic Redundancy Codes for Embedded Networks (PDF) (Thesis). Philip Koopman, advisor. Carnegie Mellon University. pp. 5, 18. Archived (PDF) from the original on 1 January 2014. Retrieved 8 July 2013.
  31. ^ «5.1.4 CRC-8 encoder (for packetized streams only)». EN 302 307 (PDF). V1.3.1. Sophia Antipolis, France: European Telecommunications Standards Institute. March 2013. p. 17. Archived (PDF) from the original on 30 August 2017. Retrieved 29 July 2016.
  32. ^ a b «8 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
  33. ^ «7.2.1.2 8-bit 0x2F polynomial CRC Calculation». Specification of CRC Routines (PDF). 4.2.2. Munich: AUTOSAR. 22 July 2015. p. 24. Archived from the original (PDF) on 24 July 2016. Retrieved 24 July 2016.
  34. ^ a b c «5.1.1.8 Cyclic Redundancy Check field (CRC-8 / CRC-16)». openSAFETY Safety Profile Specification: EPSG Working Draft Proposal 304. 1.4.0. Berlin: Ethernet POWERLINK Standardisation Group. 13 March 2013. p. 42. Archived from the original on 12 August 2017. Retrieved 22 July 2016.
  35. ^ «B.7.1.1 HEC generation». Specification of the Bluetooth System. Vol. 2. Bluetooth SIG. 2 December 2014. pp. 144–5. Archived from the original on 26 March 2015. Retrieved 20 October 2014.
  36. ^ Whitfield, Harry (24 April 2001). «XFCNs for Cyclic Redundancy Check Calculations». Archived from the original on 25 May 2005.
  37. ^ Richardson, Andrew (17 March 2005). WCDMA Handbook. Cambridge University Press. p. 223. ISBN 978-0-521-82815-4.
  38. ^ a b FlexRay Protocol Specification. 3.0.1. Flexray Consortium. October 2010. p. 114. (4.2.8 Header CRC (11 bits))
  39. ^ Perez, A. (1983). «Byte-Wise CRC Calculations». IEEE Micro. 3 (3): 40–50. doi:10.1109/MM.1983.291120. S2CID 206471618.
  40. ^ Ramabadran, T.V.; Gaitonde, S.S. (1988). «A tutorial on CRC computations». IEEE Micro. 8 (4): 62–75. doi:10.1109/40.7773. S2CID 10216862.
  41. ^ «Longwave Radio Data Decoding using and HC11 and an MC3371» (PDF). Freescale Semiconductor. 2004. AN1597/D. Archived from the original (PDF) on 24 September 2015.
  42. ^ Ely, S.R.; Wright, D.T. (March 1982). L.F. Radio-Data: specification of BBC experimental transmissions 1982 (PDF). Research Department, Engineering Division, The British Broadcasting Corporation. p. 9. Archived (PDF) from the original on 12 October 2013. Retrieved 11 October 2013.
  43. ^ Cyclic Redundancy Check (CRC): PSoC Creator™ Component Datasheet. Cypress Semiconductor. 20 February 2013. p. 4. Archived from the original on 2 February 2016. Retrieved 26 January 2016.
  44. ^ «Cyclic redundancy check (CRC) in CAN frames». CAN in Automation. Archived from the original on 1 February 2016. Retrieved 26 January 2016.
  45. ^ «3.2.3 Encoding and error checking». A signalling standard for trunked private land mobile radio systems (MPT 1327) (PDF) (3rd ed.). Ofcom. June 1997. p. 3. Archived (PDF) from the original on 14 July 2012. Retrieved 16 July 2012.
  46. ^ Rehmann, Albert; Mestre, José D. (February 1995). «Air Ground Data Link VHF Airline Communications and Reporting System (ACARS) Preliminary Test Report» (PDF). Federal Aviation Authority Technical Center. p. 5. Archived from the original (PDF) on 2 August 2012. Retrieved 7 July 2012.
  47. ^ «6.2.5 Error control». ETSI EN 300 175-3 (PDF). V2.5.1. Sophia Antipolis, France: European Telecommunications Standards Institute. August 2013. pp. 99, 101. Archived (PDF) from the original on 1 July 2015. Retrieved 26 January 2016.
  48. ^ Thaler, Pat (28 August 2003). «16-bit CRC polynomial selection» (PDF). INCITS T10. Archived (PDF) from the original on 28 July 2011. Retrieved 11 August 2009.
  49. ^ «8.8.4 Check Octet (FCS)». PROFIBUS Specification Normative Parts (PDF). 1.0. Vol. 9. Profibus International. March 1998. p. 906. Archived from the original (PDF) on 16 November 2008. Retrieved 9 July 2016.
  50. ^ a b CAN with Flexible Data-Rate Specification (PDF). 1.0. Robert Bosch GmbH. 17 April 2012. p. 13. Archived from the original (PDF) on 22 August 2013. (3.2.1 DATA FRAME)
  51. ^ «OS-9 Operating System System Programmer’s Manual». www.roug.org. Archived from the original on 17 July 2018. Retrieved 17 July 2018.
  52. ^ Koopman, Philip P. (20 May 2018). «24 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
  53. ^ «cksum». pubs.opengroup.org. Archived from the original on 18 July 2018. Retrieved 27 June 2017.
  54. ^ Boutell, Thomas; Randers-Pehrson, Glenn; et al. (14 July 1998). «PNG (Portable Network Graphics) Specification, Version 1.2». Libpng.org. Archived from the original on 3 September 2011. Retrieved 3 February 2011.
  55. ^ AIXM Primer (PDF). 4.5. European Organisation for the Safety of Air Navigation. 20 March 2006. Archived (PDF) from the original on 20 November 2018. Retrieved 3 February 2019.
  56. ^ ETSI TS 100 909 Archived 17 April 2018 at the Wayback Machine version 8.9.0 (January 2005), Section 4.1.2 a
  57. ^ Gammel, Berndt M. (31 October 2005). Matpack documentation: Crypto – Codes. Matpack.de. Archived from the original on 25 August 2013. Retrieved 21 April 2013. (Note: MpCRC.html is included with the Matpack compressed software source code, under /html/LibDoc/Crypto)
  58. ^ Geremia, Patrick (April 1999). «Cyclic redundancy check computation: an implementation using the TMS320C54x» (PDF). Texas Instruments. p. 5. Archived (PDF) from the original on 14 June 2012. Retrieved 4 July 2012.
  59. ^ Jones, David T. «An Improved 64-bit Cyclic Redundancy Check for Protein Sequences» (PDF). University College London. Archived (PDF) from the original on 7 June 2011. Retrieved 15 December 2009.

Further reading[edit]

  • Warren Jr., Henry S. (2013). Hacker’s Delight (2 ed.). Addison Wesley. ISBN 978-0-321-84268-8.

External links[edit]

  • Mitra, Jubin; Nayak, Tapan (January 2017). «Reconfigurable very high throughput low latency VLSI (FPGA) design architecture of CRC 32». Integration, the VLSI Journal. 56: 1–14. doi:10.1016/j.vlsi.2016.09.005.
  • Cyclic Redundancy Checks, MathPages, overview of error-detection of different polynomials
  • Williams, Ross (1993). «A Painless Guide to CRC Error Detection Algorithms». Archived from the original on 3 September 2011. Retrieved 15 August 2011.
  • Black, Richard (1994). «Fast CRC32 in Software». The Blue Book. Systems Research Group, Computer Laboratory, University of Cambridge. Algorithm 4 was used in Linux and Bzip2.
  • Kounavis, M.; Berry, F. (2005). «A Systematic Approach to Building High Performance, Software-based, CRC generators» (PDF). Intel. Archived (PDF) from the original on 16 December 2006. Retrieved 4 February 2007., Slicing-by-4 and slicing-by-8 algorithms
  • Kowalk, W. (August 2006). «CRC Cyclic Redundancy Check Analysing and Correcting Errors» (PDF). Universität Oldenburg. Archived (PDF) from the original on 11 June 2007. Retrieved 1 September 2006. — Bitfilters
  • Warren, Henry S. Jr. «Cyclic Redundancy Check» (PDF). Hacker’s Delight. Archived from the original (PDF) on 3 May 2015. — theory, practice, hardware, and software with emphasis on CRC-32.
  • Reverse-Engineering a CRC Algorithm Archived 7 August 2011 at the Wayback Machine
  • Cook, Greg. «Catalogue of parameterised CRC algorithms». CRC RevEng. Archived from the original on 1 August 2020. Retrieved 18 September 2020.
  • Koopman, Phil. «Blog: Checksum and CRC Central». Archived from the original on 16 April 2013. Retrieved 3 June 2013. — includes links to PDFs giving 16 and 32-bit CRC Hamming distances
  • Koopman, Philip; Driscoll, Kevin; Hall, Brendan (March 2015). «Cyclic Redundancy Code and Checksum Algorithms to Ensure Critical Data Integrity» (PDF). Federal Aviation Administration. DOT/FAA/TC-14/49. Archived (PDF) from the original on 18 May 2015. Retrieved 9 May 2015.
  • Koopman, Philip (January 2023). Mechanics of Cyclic Redundancy Check Calculations – via YouTube.
  • ISO/IEC 13239:2002: Information technology — Telecommunications and information exchange between systems — High-level data link control (HDLC) procedures
  • CRC32-Castagnoli Linux Library

Как исправить ошибку в данных CRCОшибка в данных CRC может возникнуть в самых разных случаях: при инициализации жесткого диска или работе с внешним жестким диском, картой памяти или флешкой, попытках произвести действия с накопителем в DISKPART, часто — при установке программ и игр, скачанных с торрента.

Текст ошибки также может быть разным: от простого сообщения диспетчера виртуальных дисков об ошибке в данных при инициализации диска, сообщений «DISKPART обнаружила ошибку: Ошибка в данных (CRC)» или «Расположение недоступно. Нет доступа к диску, ошибка данных (CRC)» при действиях с HDD, картой памяти или USB накопителем, до окон вида «CRC error» или «Ошибка копирования файла» с указанием на файлы устанавливаемого ПО. В этой инструкции подробно о причинах такой ошибки, что она означает и о возможных методах её исправить.

  • Что такое CRC и причины ошибки
  • Способы исправить ошибку CRC
    • При инициализации диска, форматировании, других действиях с накопителем
    • При установке игр и программ

Что такое ошибка CRC и причины ошибки

Сообщение ошибка данных в CRC при инициализации диска и доступе к диску

CRC (Cyclic Redundancy Check) или Циклический избыточный код представляет собой метод обнаружения ошибок при передаче данных с помощью контрольных сумм, используемый при обмене блоками данных с накопителями, а также в сетях, предназначенный для обнаружения изменений в передаваемых данных.

В случае с жесткими дисками и SSD, SD-картами и флешками, при обмене данными CRC используется для проверки их целостности после передачи: один и тот же алгоритм применяется к передаваемому и полученному блокам данных и в случае различного результата делается вывод об ошибках CRC.

Наиболее распространенные причины рассматриваемой проблемы:

  • Ошибка CRC для HDD и SSD, карт памяти, USB-накопителей при инициализации, форматировании, обмене данными, изменении свойств дисков:
    • Проблемы с подключением накопителя — особенно распространено для SATA-жестких дисков, внешних HDD
    • Повреждения файловой системы диска
    • Аппаратные неисправности накопителя, контроллера
    • Антивирусное ПО и другие программы, имеющие возможность менять данные в оперативной памяти
    • Проблемы с оперативной памятью, в некоторых случаях — нестабильная работа RAM или CPU в разгоне.
    • Иногда — аппаратные неисправности электронных компонентов самого компьютера или ноутбука, отсутствие заземления и статика на USB разъемах (при работе с внешними накопителями), недостаток питания для работы внешнего HDD.
  • Ошибка CRC при установке игр и программ:
    • Нарушение целостности данных при скачивании установщика
    • Аппаратные неисправности или ошибки файловой системе на диске, с которого запускается установщик
    • Ошибки при архивации установщика (установщики игр и программ — это, по сути, архивы).
    • Антивирусное ПО, особенно распространено для не самых лицензионных программ: при их установке антивирус может применять действия к подозрительным данным в памяти, что может выливаться в ошибку CRC.
    • Ошибки оперативной памяти, разгон RAM и CPU.

И отдельно про оптические диски DVD, CD, Blu-ray — ошибка в данных CRC для них может говорить о физическом повреждении записи (в том числе и самопроизвольном по истечении некоторого времени после записи), о загрязненной поверхности диска, иногда — проблемах с работой привода для чтения дисков.

Как исправить ошибку в данных CRC

В зависимости от того, в какой ситуации вы столкнулись с ошибкой CRC — при каких-либо действиях с накопителем, например, при инициализации жесткого диска или при установке игр и программ, их запуске, а также при распаковке архивов, действия будут отличаться, рассмотрим варианты решения для каждого случая.

Ошибка при инициализации жесткого диска, обращениях к внешним HDD, SSD, картам памяти и USB-накопителям

Прежде чем приступить к изложенным далее методам исправления, при наличии возможности рекомендую попробовать подключить этот накопитель к другому компьютеру или ноутбуку, а для внутренних накопителей SATA при подключении на другом устройстве — использовать другой кабель.

Если на другом компьютере диск, карта памяти или флешка работает исправно, из приведённых далее методов можно использовать только те, которые имеют отношение к самому компьютеру и операционной системе, с диском всё в порядке. Если же и на другом компьютере возникает ошибка в данных CRC, ищем проблему в самом накопителе.

Единственного рабочего метода исправить ошибку данных CRC для диска нет и иногда мы имеем дело с его аппаратной неисправностью. Среди возможных способов решения проблемы:

  1. Если на компьютере или ноутбуке ранее любым способом включался разгон памяти или процессора, отключите его. Если в последнее время менялась конфигурация, например, добавлялись модули RAM, верните исходную конфигурацию и посмотрите, не приведёт ли это к исчезновению ошибки.
  2. Проверьте работу, загрузив Windows в безопасном режиме (Как зайти в безопасный режим Windows 10). При загрузке в безопасном режиме встроенный антивирус Windows 10 и 8.1 не запускается. Если при наличии стороннего антивируса он запустился — временно отключите и его. Проверьте, сохраняется ли ошибка. Если ошибка CRC не возникает, ошибка может быть как в антивирусе (более вероятно), так и в сторонних службах и фоновых программах из автозагрузки (которые также не запускаются в безопасном режиме). Исправление ошибки CRC в безопасном режиме
  3. Следующее действие лучше всего выполнять, не выходя из безопасного режима. Если диск с ошибкой инициализирован и ему присвоена буква, запустите командную строку от имени администратора и введите следующую команду, заменив букву диска D на свою (подробнее: Проверка жесткого диска на ошибки).
    chkdsk D: /f /r

    Выполнение команды может занять очень продолжительное время, не выполняйте при питании от батареи на ноутбуке.

  4. Если недавно проблема не возникала, попробуйте использовать точки восстановления системы на случай, если ошибка вызвана проблемами с конфигурацией ОС в реестре.
  5. Для внешнего USB диска и флешки — используйте разъёмы на задней панели ПК и не используйте USB-хабы (разветвители портов), попробуйте использовать разъем USB 3.0 вместо 2.0 или наоборот. При наличии дополнительных кабелей для подключения дисков, проверьте их в работе.
  6. Если конструкция внешнего диска позволяет его разобрать и извлечь накопитель — сделайте это и проверьте работу накопителя при прямом подключении к компьютеру кабелем SATA (не забывая про кабель питания).
  7. Для SATA жестких дисков — попробуйте использовать другой кабель для подключения. При отсутствии свободных кабелей можно использовать необязательный, например, от привода оптических дисков. Кабели SATA для подключения жестких дисков
  8. Если у вас ПК и к нему подключено большое количество жестких дисков и/или SSD, временно отключите все необязательные и проверьте, повлияет ли это действие на ситуацию.
  9. Для SSD — установите официальную утилиту от производителя для вашей модели накопителя: возможно, в ней будет информация о неисправности, иногда — возможность обновить прошивку (возможно, не стоит выполнять), про такие программы: Программы для SSD дисков.

    Внимание: при рассматриваемой ошибке обновление прошивки может привести и к полной неработоспособности диска.

  10. Если данные на накопителе не представляют ценности, вы можете: для жестких дисков и SSD попробовать выполнить форматирование средствами системы, для карт памяти и USB накопителей, можно попробовать выполнить форматирование в Windows, в других устройствах (смартфоны, фотоаппараты) использовать специальные программы для ремонта флешки.

Одно из решений должно позволить исправить ошибку в данных CRC, при условии, что мы не имеем дело с аппаратной неисправностью диска. Если к настоящему моменту времени работа диска не была проверена на другом компьютере — найдите возможность сделать это, а при сохранении проблемы от использования накопителя придется отказаться.

Если диск содержит важные данные и инициализируется в системе, вы можете использовать бесплатные программы для восстановления данных (с большой вероятностью подойдет DMDE в режиме просмотра содержимого томов), если не инициализируется — останется обратиться в специализированную лабораторию для восстановления.

Ошибка возникает при установке игр и программ или при их запуске

Ошибка в данных CRC при установке игры

В случае, если ошибка в данных CRC появляется при попытках установить или запустить какое-либо программное обеспечение, возможными вариантами решения будут:

  1. Отключение вашего антивируса, повторная загрузка установщика игры или программы, добавление папки с установщиком и папки, куда производится установка в исключения антивируса, запуск установки.
  2. Загрузка установщика из другого источника.
  3. В случае если не запускается программа, которая раньше работала — использование точек восстановления системы при их наличии, переустановка программы.
  4. Отключение разгона оперативной памяти и процессора, отключение утилит для очистки оперативной памяти при их наличии.
  5. Проверка жесткого диска на ошибки командой из 3-го шага предыдущего раздела.
  6. Загрузка установщика программы на другой физический диск, если на компьютере их более одного.
  7. В случае недавнего изменения аппаратной конфигурации компьютера, добавления или замены RAM, попробуйте вернуть исходную конфигурацию и проверить, сохраняется ли ошибка.
  8. В редких случаях причиной проблемы могут быть символы кириллицы в пути к файлу установщика или в пути к месту установки: проверьте, сохранится ли ошибка если исключить кириллицу в именах папок и полных путей к этим расположениям.

И, в завершение, если один из способов помог в исправлении ошибки в данных CRC, буду благодарен вашему комментарию с описанием ситуации и решения: это поможет составить статистику, которая будет полезной другим читателям.

In 1961, the American mathematician William Wesley Peterson developed cyclic redundancy checking (CRC) to reduce errors occurring when transmitting and storing data. In this procedure, redundancies are added to each data block in the form of an additional test value. This value, also known as the CRC value, makes it possible to detect errors that have occurred during transmission and storage and would ideally correct them automatically.

If the cyclic redundancy check encounters at least one problematic file, a CRC error may occur that prevents the scheduled data storage or transfer from being executed. This can occur especially when downloading and extracting compressed files and archives. However, it can also happen when reading and writing data to hard disks. In this article, we’ll discuss what a CRC error is and how to resolve the problem.

Contents

  1. What is a CRC error?
  2. What can be done to prevent a CRC error?
    1. CRC error: here’s how to fix it when extracting files
    2. Extracting a file despite a CRC error (using WinRAR)
    3. CRC errors during read or write processes — possible solutions
  3. Can CRC errors be avoided?

What is a CRC error?

A CRC error informs you that the cyclic redundancy check has detected damaged or incomplete files. In that case, the matched value of the data and the attached CRC value do not match, resulting in an aborted action (save, copy, read access, etc.) and a corresponding CRC error message. Typically, this message is as follows:

Data error (cyclic redundancy check)

The CRC error often occurs when extracting compressed files and archives. A failed cyclic redundancy check may also happen when reading and writing to local and external hard disks or USB sticks as well as CDs, DVDs or Blu-rays.

In order to protect your privacy, the video will not load until you click on it.

What can be done to prevent a CRC error?

If you encounter a CRC error, it can be really annoying. Your go-to solutions such as rebooting the system won’t help solve a CRC error. You can’t temporarily disable the checking procedure either, which is why theaffected files seem lost at first. However, depending on the context, there are different strategies to solve the problem and save your files!

CRC error: here’s how to fix it when extracting files

If you want to extract compressed files, you can use the tools installed on your operating system. Many users do opt for third-party tools such as WinZip or WinRAR for packing and extracting documents, however, which often have a much greater range of functions. If you use this kind of software yourself, you should first check whether it is still up to date when your CRC error occurs. If you have updated the program and the error persists, try to reinstall it entirely. A change of program can also be the answer to your CRC problem.

Tip

Even an incomplete or incorrectly executed download can quickly lead to problems like a CRC error. If you have downloaded the corrupted file or archive from the Internet, we recommend that you download it again.

Many third-party tools can repair damaged archives or compressed files. If your program offers this option, you can try to fix the CRC error this way in the last step. For example, in WinRAR, you can start the repair as follows:

  1. Open the zipped file in WinRAR.
  2. Click on the “Tools” item in the upper menu bar.
  3. Select “Repair archive”.
  4. Specify a location for the archive to be repaired and specify the compression type (ZIP or RAR).
  5. Confirm to begin the repair.
  6. When the process is complete, there is a rebuilt variant of the archive in the defined target directory, which should not cause a CRC error during extraction.
Repair Archive in WinRAR
Repair the faulty archive with WinRAR. This way, you’ll have a good chance of fixing a CRC error.

Extracting a file despite a CRC error (using WinRAR)

If a compressed file can no longer be extracted due to a CRC error, often most of the data is fine, and only a few files are corrupted. You could save the uncorrupted files even if you can’t fix the CRC error entirely. As an example, the following instructions show how this procedure works in WinRAR:

  1. Open the affected archive with WinRAR.
  2. Press the menu item “Extract to”.
  3. Mark the option “Keep broken files” in the “Miscellaneous” section.
  4. Confirm to finish this step.
  5. The files will then be extracted to the defined target directory — including the broken file(s). However, these files cannot be opened or edited.
WinRAR: Extracting options
After activating the option “Keep corrupted files”, WinRAR will unzip the damaged files without issue.

CRC errors during read or write processes — possible solutions

Because there is no specific troubleshooting for storage media errors, tools for general error checking of the affected media have the best chance of success. As with WinRAR, you can choose between third-party software (usually for a fee) and tools that are already integrated in your system. In Windows operating systems, the tool can be found under “error checking”. This comes preinstalled. It can be used in the following way for data problems, such as a CRC error:

  1. Open the File Explorer and select the problematic disk drive by right-clicking on it.
  2. Select the menu item “Properties”.
  3. Switch to the “Tools” tab.
  4. Click on the “Check” button under the “Error checking” options.
  5. Finally, press the “Scan Drive” button to start the error check.
Disk Error Checking in Windows 10
Note that if you want to use the Windows tool “Error Checking” to fix CRC errors, you need administrator rights.

Can CRC errors be avoided?

Problems with extraction or reading and writing of files are particularly serious if the files are required urgently. The fundamental question is whether it is possible to prevent errors resulting from the cyclic redundancy check in the first place. However, there is no proper answer in this case, unfortunately. Files or archives can be damaged at any time. However, you can make an effort to keep software for handling files up to date by regularly checking for available updates and installing them.

In addition, you can generally minimize the risk of hardware problems by always shutting down your device properly and disconnecting external hard drives and USB sticks using the “Safely Remove Hardware” feature.

Related articles

Converting ACSM files

Opening and converting ACSM files

Sellers of e-books and other electronic publications face the same problem as the creators and copyright owners of films, music and software – because the content is digital, it is easy to reproduce and redistribute. To prevent this, commercial ePUBs, PDFs and other files are copy-protected, for example using Adobe Digital Rights Management (DRM). This is where ACSM files come into play.

Opening and converting ACSM files

WinRAR alternatives

WinRAR alternatives: Comparing the best solutions

If you want to send large files as an e-mail attachment, you have to compress them first. Zipped in small, handy containers, these packed files are not unzipped until they reach their destination. Besides the well-known WinRAR, there are a few other alternatives worth checking out for zipping and unzipping files. We’ll show you the advantages and disadvantages of the best WinRAR alternatives here….

WinRAR alternatives: Comparing the best solutions

File systems

File systems: explanation and overview of the most important ones

Usually, users have little reason to engage with the file system on their computer. However, it’s worth having an understanding of the topic, because hardware performance, data security, and compatibility with other devices and network-based data exchange depend on file systems.

File systems: explanation and overview of the most important ones

Windows и ошибки идут рука об руку. Большинство этих ошибок просто исправить, на что вам не придется тратить и двух минут. Однако если это ошибка, связанная с вашими данными, все может стать немного запутанным. Ошибка в данных crc является одной из таких ошибок. Но прежде всего, что такое crc? Циклическая проверка избыточности(crc) — это своего рода проверка, выполняемая вашим устройством для проверки точности исходных данных на различных устройствах хранения. Если эта проверка по какой-либо причине не проходит, это приводит к ошибке данных (crc). Эту ошибку нельзя игнорировать, поскольку она делает невозможным доступ к хранящимся на устройстве данным. К счастью, существует несколько способов, с помощью которых вы можете избавиться от этой проблемы, и мы перечислили их все в этом руководстве, давайте рассмотрим их по порядку.

циклическая проверка избыточности ошибок данных

1. Что такое Ошибка данных Циклической проверки избыточности?

Как упоминалось ранее, циклическая проверка избыточности — это механизм контроля со стороны системы для проверки точности необработанных данных на вашем устройстве. Если проверка не может сопоставить контрольные значения обработанного файла с существующим, это приводит к тому, что мы знаем как ошибка циклической проверки избыточности данных ssd.

2. Что Вызывает Ошибку Циклической Проверки Избыточности Данных?

Этой ошибке может способствовать множество факторов, наиболее распространенными из которых являются проблемы, связанные с сетью или хранилищем. Некоторые из известных причин включают:

  • Поврежден раздел, приложение, файл или устройство хранения.
  • Устройство, подключенное к нестабильной или неисправной сети.
  • Изменения метаданных файлов или имени файла во время использования.
  • Изменения в файле реестра.
  • Резкое отключение.
  • Неправильно подключенный жесткий диск.

Часть 2: Как Мне Исправить ошибку в данных crc?

Подготовка: Восстановление данных с жесткого диска с ошибкой crc

Жесткий диск, пораженный ошибкой данных циклическая проверка избыточности ошибка внешнего жесткого диска сопряжена с высоким риском потери всех данных. У вас должно быть готово решение для извлечения данных, если они будут потеряны. Таким решением является восстановление данных Tenorshare 4DDiG. Быстрый и компактный инструмент, предназначенный для восстановления данных практически в любой ситуации, 4DDiG — это единственное, что вам нужно для извлечения данных после исправления ошибки CRC. Следуйте этим простым шагам, чтобы вернуть свои данные в кратчайшие сроки.

  • Восстановление файлов с недоступных устройств циклической проверки избыточности.
  • Восстановление файлов с внутреннего/внешнего HDD/SSD, SD-карты, USB-накопителя, SD-карты и т. д.
  • Поддержка более 1000 типов файлов, таких как фотографии, видео, документы и многое другое.
  • Поддерживает файловые системы, включая такие, как FAT16, FAT32, exFAT, NTFS, APFS и HFS+.
  • 100% простота и безопасность.
  • Шаг 1:Выберите жесткий диск
  • Подключите внешний накопитель и найдите его на 4DDiG. Затем нажмите кнопку сканировать, чтобы продолжить. В следующих всплывающих окнах вы можете настроить типы файлов, чтобы начать сканирование.

    выберите клонированный жесткий диск

  • Шаг 2:Сканировать жесткий диск
  • 4DDiG немедленно проверяет выбранный диск на предмет отсутствия данных, и вы можете приостановить или прекратить поиск в любое время, если определили файлы, которые хотите восстановить. В древовидном представлении есть такие категории, как Удаленные файлы, Существующие файлы, Потерянное местоположение, Необработанные файлы и Файлы тегов. Вы также можете переключиться в режим просмотра файлов, чтобы проверить такие типы файлов, как Фото, видео, Документ, Аудио, электронная почта и другие. Кроме того, вы можете искать целевые файлы или использовать фильтр, чтобы сузить область поиска в левой части панели.

    сканирование локального диска

  • Шаг 3:Предварительный просмотр и восстановление файлов
  • После обнаружения целевых файлов вы можете просмотреть их и восстановить в безопасном месте. В случае перезаписи диска и необратимой потери данных, пожалуйста, не сохраняйте их в том же разделе, где вы их потеряли.

    выберите сохранить местоположение

После восстановления данных теперь вы можете приступить к исправлению этой ошибки.

Исправление 1: Запустите проверку диска для устранения неполадок

Самое замечательное в Windows то, что в ней есть множество инструментов, которые вы можете использовать для устранения ошибки циклической проверки избыточности данных ошибка жесткого диска. Проверка диска — один из них и один из самых безопасных для сохранения ваших данных во время исправления. Вот как вы можете его использовать.

Шаг 1: Перейдите в раздел «Мой компьютер», щелкните правой кнопкой мыши раздел с ошибкой и перейдите в раздел «Свойства».

Шаг 2: Оказавшись в окне свойств, перейдите на вкладку Инструменты и нажмите опцию «Проверить сейчас» в разделе проверка ошибок.

исправить ошибку данных (циклическая проверка избыточности) - выполнить проверку диска

Шаг 3: Теперь вы можете выбрать сканирование диска для устранения неполадок и устранения ошибки CRC.

Исправление 2: Используйте утилиту CHKDSK для восстановления жесткого диска

CHKDSK — это утилита для решения большинства проблем, связанных с данными в Windows, и diskpart столкнулся с ошибкой ошибка данных (циклическая проверка избыточности) ничем не отличается. Чтобы использовать CHKDSK для решения этой проблемы, выполните следующие действия:

Step 1: Откройте командную строку и выберите запуск от имени администратора. Введите следующую команду: chkdsk /r x:‘. Здесь x — это конкретный диск, который выдает вам ошибку.

ошибка данных циклическая проверка избыточности внешнего жесткого диска - запустите утилиту CHKDSK

Step 2: Утилита CHKDSK теперь просканирует раздел, выдаст вам отчет и перезагрузит ваш компьютер. Ваше устройство будет исправлено при запуске, если этот метод сработает. Если нет, переходите к следующему.

Исправление 3: Запустите SFC-сканирование для восстановления системных файлов

Если источником этой ошибки является логическая проблема с вашим жестким диском, то проверка системных файлов (SFC) также может решить вашу проблему. Вот как это делается:

Step 1: Запустите командную строку от имени администратора и введите следующую команду «sfc /scannow«.

ошибка данных циклическая проверка избыточности ssd - запустите SFC-сканирование

Step 2: Теперь начнется сканирование, которое устранит проблему.

Исправление 4: Форматирование устройств

Если вы используете жесткий диск Seagate или любой другой компании и все еще не можете обойти ошибку циклической проверки избыточности данных ошибка внешнего жесткого диска seagate, то пришло время отформатировать ваш жесткий диск.

Step 1: Откройте Панель управления и перейдите в раздел Управление компьютером.

Step 2: В приложении «Управление дисками» выберите раздел для форматирования и щелкните по нему правой кнопкой мыши. В появившемся меню выберите опцию Форматирования.

Step 3: Теперь появится окно форматирования, в котором вам нужно будет выбрать тип формата, который вы хотите выполнить, и другие связанные с этим вещи. Нажмите кнопку ОК, и начнется процесс форматирования.

ошибка данных циклическая проверка избыточности жесткого диска - отформатируйте диск

Советы: Если вы отформатируете диск, данные на нем будут удалены. Не беспокойтесь, скачайте Tenorshare 4DDiG data recovery, чтобы без особых усилий восстановить все потерянные файлы с отформатированного диска.

Исправление 5: Перейдите к ручному ремонту

Если ни один из вышеперечисленных методов не работает, вам следует связаться с зарегистрированными дилерами вашего устройства или жесткого диска и попытаться починить его там.

Часть 3: Как предотвратить ошибку в данных crc внешнего жесткого диска?

Исправления, приведенные в этом руководстве, решат вашу проблему, но вы несете ответственность за предотвращение повторения ошибки циклической проверки избыточности данных диспетчера виртуальных дисков. Для этого вы можете применить на практике следующие пункты.

  • Регулярно сканируйте свое устройство с помощью защитника Windows и поддерживайте его в актуальном состоянии.
  • Выключите и правильно включите устройство. Избегайте резких отключений.
  • Не вмешивайтесь в реестр или метаданные вашего устройства.
  • В любой момент времени сохраняйте 20% бесплатных данных в своей системе.
  • Используйте только подлинную копию Windows.

Часть 4: Часто задаваемые вопросы по теме

1. Как я могу исправить ошибку в данных crc для жесткого диска, который не инициализирован?

Чтобы исправить ошибку данных циклическая проверка избыточности ошибка инициализации диска, вы можете использовать утилиту CHKDSK. Откройте командную строку и введите команду ‘chkdsk /r x:‘, где x — имя диска, и запустите ее.

2. Как мне исправить crc без указания буквы диска?

Если вы не можете найти букву диска вашего жесткого диска, обновите все драйверы, связанные с жестким диском, и перезагрузите компьютер.

3. Как мне исправить ошибку в данных crc нераспределенной?

Вы можете исправить ошибку циклической проверки избыточности данных, нераспределенную упомянутыми здесь исправлениями:

  • Запустите Проверку диска для устранения неполадок
  • Используйте утилиту CHKDSK для восстановления жесткого диска
  • Запустите SFC-сканирование для восстановления системных файлов
  • Форматирование устройств
  • Перейдите к ручному ремонту

Заключение:

Это было все, что вам нужно было знать о досадной ошибке циклического резервирования. Начиная с причин и заканчивая решением, мы изложили все самое важное вместе с чрезвычайно важным средством восстановления данных — Tenorshare 4DDiG Data Recovery. Это гарантирует, что ваши проблемы будут устранены без потери даже байта данных в процессе. Все это и многое другое без каких-либо затрат. Так чего же вы ждете?

Вам Также Может Понравиться

  • Home>>

  • Диск >>
  • Как исправить ошибку в данных crc?

Пользователи регулярно сталкиваются с различными системными сбоями, возникающими по программным или аппаратным причинам. Одной из распространённых проблем является ошибка CRC, сопровождающаяся сообщением с соответствующим текстом «Ошибка данных в CRC». Она свидетельствует о несовпадении контрольных сумм загружаемого файла, что говорит о его изменении или повреждении, и может проявляться при использовании внутренних и внешних накопителей информации. Часто сбой встречается во время записи оптического диска, копирования данных с диска на компьютер, установке игр и приложений или при работе с торрент-клиентами. Момент отслеживания появления сбоя всегда имеет значение, поскольку способ решения проблемы напрямую зависит от того, при каких условиях возникла ошибка CRC.

Ошибка в данных CRC на компьютере

Что такое CRC

Циклический избыточный код или CRC (англ. Cycle Redundancy Check) является алгоритмом вычисления контрольной суммы файла, используемой для проверки корректности передаваемой информации. То есть в результате обработки информации получается определённое значение, которое обязательно будет разным для файлов, даже на один бит отличающихся между собой. Так, алгоритм, базирующийся на циклическом коде, определяет контрольную сумму и приписывает её к передаваемым данным. В свою очередь принимающая сторона также владеет алгоритмом нахождения контрольной суммы, что даёт возможность системе проверить целостность получаемых данных. Когда эти числа соответствуют, информация передаётся успешно, а при несовпадении значений контрольной суммы возникает ошибка в данных CRC, это означает, что файл, к которому обратилась программа, был изменён или повреждён.

Ошибка данных CRC

Причины возникновения ошибки CRC

В большинстве случаев проблема носит аппаратный характер, но иногда возникает и по программным причинам. Сообщение «Ошибка данных в CRC» может говорить о неисправности HDD, нарушении файловой системы или наличии битых секторов. Нередко сбой возникает при инициализации жёсткого диска или твердотельного накопителя SSD после подсоединения к компьютеру, несмотря на конструктивные отличия и разницу в способе функционирования, это происходит, поскольку не удаётся правильно прочитать данные. Тогда неполадка может заключаться не только в механических повреждениях, но и в неисправности интерфейсов подключения или плохом контакте. Ошибка в устройствах SSD с интерфейсом PCI-E также случается из-за накопившихся загрязнений на плате. Проблемы с доступом к внешним накопителям нередко связаны с неисправностью портов. Среди программных причин ошибку в данных CRC способны вызывать сбои драйверов устройств. Источником проблемы при установке программного обеспечения посредством торрент-клиента чаще всего является повреждённый архив. Таким образом, можно выделить следующие причины ошибки CRC:

  • Случайный сбой во время установки софта.
  • Потеря или повреждение данных при их передаче.
  • Загрузка повреждённого архива.
  • Неправильные записи системного реестра.
  • Некорректные драйверы устройств.
  • Повреждение оптического диска.
  • Неисправность разъёмов.
  • Повреждение секторов жёсткого диска, файловой системы HDD.
  • Неправильная конфигурация файлов и другие причины.

Ошибка CRC при установке игры

Как исправить ошибку CRC

Факторов, провоцирующих проблему не так уж и мало. Определить источник неприятности чаще всего можно исходя из условий, при которых проявилась ошибка в данных CRC, тогда можно сузить круг возможных причин и понять, как исправить сбой. Все действия, направленные на устранение неисправности будут эффективны в различных ситуациях.

Ошибка в данных CRC при подключении устройства

В случае возникновения проблемы при работе с внешними накопителями прежде, чем лечить устройство посредством специализированных утилит, первым делом следует проверить работу с другими разъёмами. Если порт неисправен, то вопрос может решиться подключением носителя к иному порту на девайсе. Ещё одна причина – плохой контакт, например это часто встречается в адаптере подключения SD карты, а также при использовании устройств HDD или SSD. Флешка, СД карта или другой подключаемый накопитель также могут быть неисправными, для чтения данных с повреждённых устройств используется специальный софт, например, BadCopyPro, но при выходе из строя носителя программные методы бессильны.

Возникновение сбоя при попытке доступа к файлам на HDD

«Ошибка в данных CRC» нередко проявляется по причине нарушения целостности файловой системы или битых секторов на жёстком диске. Поскольку не удаётся правильно прочесть информацию, с этим может быть связан ряд сбоев, включая ситуацию, когда винчестер не инициализируется. Диагностировать HDD можно с помощью встроенных средств Windows или сторонних программ.

Проверка инструментом Chkdsk

В арсенале ОС имеется немало интегрированных служб для решения различных задач. Проверить файловую систему на ошибки, а также обнаружить битые сектора можно с использованием утилиты Check disk, вызываемой из командной строки. Чтобы просканировать жёсткий диск выполняем следующие действия:

В ряде случаев, когда нет доступа ко всему диску или ошибка в данных CRC проявляется при обращении к софту, который раньше работал, сканирование потребуется выполнить в режиме восстановления, для чего потребуется загрузочная флешка или диск с соответствующей ОС Windows. Изменив порядок запуска устройств (выставить в Boot приоритет для съёмного накопителя) и запустившись с загрузочного носителя можно открыть командную строку следующим образом:

Сканирование системной утилитой проверки диска

Можно выполнить проверку на ошибки и другим способом:

При выборе системного диска потребуется запланировать проверку, в таком случае он будет просканирован при следующей загрузке Windows. Для восстановления HDD применяется также сторонний софт, например, HDD Regenerator, Acronis Disk Director, Victoria и прочие. При этом в случае с физическими повреждениями устройства выправить их программно не получится, поэтому лучше заранее скопировать важную информацию с жёсткого диска, возможно, его время уже на исходе.

Проблема при скачивании с CD/DVD носителя

Если ошибка выскакивает при копировании информации с оптического диска на внутренний накопитель, возможно, что диск просто загрязнён или повреждён. Для начала нужно очистить поверхность носителя и попытаться выполнить процедуру снова. Если не помогло, ищем другой источник информации, а при его отсутствии и необходимости восстановления данных с диска можно использовать программу BadCopyPro, которая считывает и возвращает к жизни файлы с испорченных накопителей, если это возможно. К сожалению, при сильно выраженных повреждениях диска скопировать с него файлы не удастся.

Программа BadCopyPro

Ошибка в данных CRC при записи оптического диска, установке программ или игр

Если проблема возникла в процессе записи образа, скачанного с просторов интернета, на CD/DVD, стоит проверить контрольные суммы записываемых данных перед выполнением процедуры. Для этой цели используется утилита HashTab, после установки которой, в свойствах файла появится новая вкладка «Хеш-суммы файлов», с её помощью вы сможете сравнить значение с исходником. Так, при несовпадении контрольных сумм, следует скачать образ снова.

Утилита HashTab для ПК

Повторно скачать файл или архив следует также, когда с помощью скачанного дистрибутива программы она не устанавливается на компьютер. Данные могли быть повреждены в процессе загрузки или не были полностью выкачаны. Удобно применять для скачивания uTorrent, поскольку утилита самостоятельно определяет значения контрольных сумм и перекачивает часть информации, загрузившейся с ошибкой. В случае скачивания данных по прямым ссылкам можно использовать Download Master. При этом не исключено, что архив или файл уже был повреждён изначально и в таком виде залит на ресурс, потому нужно попробовать скачать его с альтернативного источника.

Скачивание файла по ссылке в Download Master

Ошибка в uTorrent

Когда ошибка в данных CRC появляется в программе uTorrent, исправляем её следующими действиями:

  • Выполняем обновление клиента.
  • Удаляем проблемную раздачу в программе, а также недокачавшийся файл в папке на компьютере.
  • Ищем аналогичную раздачу на другом ресурсе и скачиваем оттуда.

Проверка обновлений в uTorrent

Установка найденных обновлений в uTorrent

Вышеперечисленных способов достаточно, чтобы избавиться от ошибки в данных CRC, возникающей при различных условиях. Так, определив источник появления сбоя, можно целенаправленно устранить проблему. В большинстве случаев исправить ошибку удаётся программными средствами, но, когда речь идёт о физической неисправности накопителя, следует задуматься о его замене.

Добавлено 25 ноября 2018 в 23:07

В данной статье кратко объясняется, что такое CRC, и как вы можете использовать его, чтобы сделать вашу цифровую связь более надежной.

Мир сейчас полностью зависит от хранения и передачи цифровых данных. Самолеты, фондовые рынки, системы безопасности, скороварки – современная жизнь быстро обрушится в хаос, если мы не сможем обеспечить точность в постоянно текущем и необъятно огромном потоке из единиц и нулей.

Есть две основные задачи, связанные с поддержанием целостности наших цифровых данных. Первое – это избегать в первую очередь ошибок; эта цель включает в себя множество инженерных практик, которые способствуют надежной передаче и приему цифровых данных. Но, несмотря на все наши усилия, ошибки возможны, и это приводит нас ко второй задаче: обнаружение ошибок. Если система может обнаруживать ошибки, она также может компенсировать эти ошибки, просто отбросив сомнительные данные или запросив повторную передачу.

Выбор метода обнаружения ошибок

Если вы знакомы с битом четности, который иногда используется в связи через UART, вы что-то знаете об обнаружении ошибок. Но бит четности является довольно жалким механизмом обнаружения ошибок; на самом деле, насколько я могу судить, большинство методов обнаружения ошибок более или менее жалки по сравнению с циклическим избыточным кодом (CRC, cyclic redundancy check), который явно стал доминирующим подходом – некоторые крупные имена в цифровой связи (включая CAN, USB и Ethernet) используют CRC как часть своего протокола передачи данных.

Структура пакета данных USB

Структура пакета данных USB

Эффективный, но не простой

Эта короткая статья не является местом для изучения подробностей вычислений и производительности CRC. Суть в том, что двоичный «многочлен» применяется к потоку данных таким образом, чтобы генерировать контрольную сумму, которая, скорее всего, изменится, если один или несколько битов сообщении были изменены.

Этот «многочлен» представляет собой просто математически удобный способ обращения к определенной последовательности битов. Например:

(x^{16}+x^{12}+x^5+1=0001 0000 0010 0001)

Это широко используемый полином «CCITT». Это полином 16-го порядка, что означает, что соответствующее двоичное число имеет ширину 16 бит, и что итоговая контрольная сумма CRC будет иметь ширину 16 бит. (Обратите внимание, что коэффициент для члена высшего порядка считается равным 1 и опускается в двоичной версии.) Члены, которые не отображаются в математическом выражении, имеют в качестве коэффициента двоичный 0.

Обнаружение ошибок проще и эффективнее с аппаратным CRC модулем; это схема из технического описания EFM8LB1 показывает работу CRC периферии в микроконтроллере EFM8 Laser Bee

Обнаружение ошибок проще и эффективнее с аппаратным CRC модулем; это схема из технического описания EFM8LB1 показывает работу CRC периферии в микроконтроллере EFM8 Laser Bee

Два CRC, не один

Создание CRC только для исходного сообщения вам не поможет. Ключом к реализации обнаружения ошибок CRC является обеспечение того, чтобы и передатчик, и приемник генерировали контрольную сумму одним и тем же способом.

Передатчик генерирует контрольную сумму для передаваемых данных и включает ее в исходное сообщение, а приемник генерирует собственную контрольную сумму с использованием полученных данных. Если сообщение приемника не совпадает с сообщением передатчика, весьма вероятно, что контрольные суммы будут отличаться; таким образом, приемник считает данные ошибочными, если контрольные суммы CRC не совпадают.

Куда двигаться дальше

Вы должны знать, что обработка CRC может использоваться фактически для исправления ошибок, а не просто для их обнаружения. Здесь мы имеем дело с двоичными данными, поэтому, если CRC позволяет нам идентифицировать ошибочный бит, мы можем восстановить исходную информацию, просто переключив этот бит.

В следующих статьях мы рассмотрим подробности исправления ошибок на базе CRC.

Теги

CRC (циклический избыточный код)Исправление ошибокКонтрольная суммаОбнаружение ошибокЦифровая связь

Ошибка в данных CRC — циклическая проверка избыточности ошибок данных возникает, когда пользователь Windows переносит данные с одного диска на другой. Ошибка CRC возникает при копировании файлов с SD-карт памяти и USB-флешек. Она может появляться, когда пользователь устанавливает игру с флешки или при подключении внешнего диска.

CRC (Cyclic Redundancy Check) — алгоритм, который использует проверку точности данных при копировании на HDD/SSD дисках, оптических, SD-картах памяти, USB флешек. CRC обнаруживает случайные изменения необработанных данных, находящихся в хранилище и выдает ошибку, если контрольные суммы различаются.

Другими словами, когда копируются данные с флешки на диск, то они передаются небольшими блоками, и каждому блоку присваивается значение CRC. Если что-то пойдет не так с данными в период, как они покинут источник и прибудут в пункт назначения, CRC, отправленный в источник, больше не будет соответствовать назначенной контрольной сумме, что и вызывает ошибку данных CRC.

Ошибка в данных CRC

Как исправить ошибку данных CRC

Виновником CRC ошибки является неисправность самого устройства, плохие сектора на диске, конфигурация реестра, драйвер или неудачное установленное ПО. Разберем способы, как устранить ошибку CRC при инициализации диска или копировании файлов с флешки на диск.

1. Вирусы и антивирус

  1. Во многих случаях, сторонний антивирус может блокировать файлы при копировании, что вызовет сбой и ошибку данных CRC.
  2. Вирусы могут повредить некоторые системные файлы или файлы при копировании. В данном случае, лучше воспользоваться сторонним сканером как DrWeb или Zemana.

2. Плохие сектора

Ошибки секторов на диске, флешке или SD карте это главный виновник проблемы, когда появляется ошибка в данных CRC. Чтобы устранить проблему, запустите командную строку от имени администратора и введите ниже команду, которая проверит и автоматически восстановит плохие сектора на диске или другом устройстве.

  • chkdsk C: /f /r /x

Вместо C: укажите то устройство на котором ошибка в данных CRC. В некоторых случаях, после ввода команды, нужно будет нажать Y и перезагрузить ПК.

CHKDSK проверка и восстановление жесткого диска

3. Проверка системных файлов

Поврежденные системные файлы или недостающие могут быть виновником ошибки данных CRC. Запустите командную строку от имени администратора и введите ниже 2 команды по очереди.

sfc /scannow
DISM /ONLINE /CLEANUP-IMAGE /RESTOREHEALTH

Запуск SFC в CMD

Примечание к способу 2 и 3

Если у вас выдаются ошибки при вводе команд, то вы можете загрузиться через дополнительные параметры и запустить командную строку. Вы также можете создать установочную флешку с Windows 10 для запуска CMD.

Запуск командной строки при установки Windows 10

4. Сброс файловой системы

Этот метод удалит все данные с вашей флешки или диска и не рекомендуется тем пользователям, которые не хотят потерять важные файлы.

  • Нажмите правой кнопкой мыши по диску или флешке, которая выдает ошибку в данных CRC и выберите «Форматировать«.
  • В окне укажите NTFS, если диск или флешка больше 32 ГБ, и нажмите «Начать«.
  • Если внешний диск или флешка меньше 32 Гб, то выберите FAT32.

форматировать флешку в другую файловую систему

5. Если не видно букву диска

Нажмите Win+R и введите devmgmt.msc, чтобы открыть диспетчер устройств. Разверните графу «Дисковые устройства» и, если будет желтый восклицательный знак на диске или флешке, то нажмите провой кнопкой мыши по данному устройству и выберите «Обновить драйвер«.

channel

В противном случае нажмите правой кнопкой мыши по графе «Дисковые устройства» и выберите «Обновить конфигурацию оборудования«.

Если буква диска еще не появилась, то обратитесь к подробному руководству.

дисковые устройства обновить конфигурацию оборудования

6. Иры и ПО

Если имеется какое-либо ПО связанное с диском или флешкой, которое может работать в фоновом режиме, то его следует удалить и посмотреть, устранена ли ошибка. Если ошибка CRC появляется при установке игры, то скорее всего при скачивании самой игры были повреждены некоторые файлы. В данном случае нужно скачать игру заново. Это касается и торрент скачивания.


Смотрите еще:

  • Медленная скорость передачи данных по USB 3.0 в Windows 10
  • Как снять защиту от записи с USB флешки и карт памяти
  • На флешке не видны файлы и папки Windows 10
  • Не удалось инициализировать драйвер этого устройства (Код 37)
  • На диске недостаточно места для выполнения этой операции

[ Telegram | Поддержать ]

The cool thing about programming is that there is an absolute truth in every Bit: It’s either black or white, 1 or 0, true or false. In theory. But whenever you transmit data or store it somewhere on a physical drive, it can get corrupted. Individual bits can get flipped or even bursts of multiple bits, changing the value and the meaning of your data inadvertently. Surrounding electromagnetic radiation can interfere with your Bluetooth or wi-fi signals and cause unintended changes in your data stream. Simply accessing a flash memory might also result in bit flips.

So whenever you exchange data with other systems, how do you make sure that the data you receive is exactly the same as the data that was sent to you? How do you detect accidental changes in your data stream? Or in other words, how do you check the integrity of your data against unintended changes and losses?

There are a number of mechanisms used for data error detection. The most common one is called Cyclic Redundancy Check (CRC). It is often used in Bluetooth and other wireless communication protocols. It is also used to check the integrity of different types of files such as Gzip, Bzip2, PNG etc. The name sounds rather complex and intimidating. However, after reading this article you should have a good understanding of what a CRC is and how it works.

The Basics

CRC is an error detection code used for verifying the integrity of data. It works just like a checksum and is appended to the end of the payload data and transmitted (or stored) along with that data.

For example, let’s say we want to send the lower-case letter z to someone else. In Unicode, the z is represented by the number 0x7A, that’s 0111 1010 in binary representation. In order to make it possible for the receiver to verify that the data wasn’t modified on transmission, we calculate the CRC for this data (1000) and simply append it to our message:

0111 1010 (data) → 0111 1010 1000 (data + CRC)

The check value is called redundant because it doesn’t add any additional information to the message. (This data is only appended for the sake of error detection and data integrity). 0111 1010 contains the same information as 0111 1010 1000 (where last 4 bits are the CRC), however, in the first case, the receiver has no way of verifying if the data was received correctly.

CRCs are specifically designed to detect common data communication errors. It can also detect when the order of the bits or bytes changes. CRCs can easily be implemented in hardware – another reason for their widespread use. Before we take a deep dive into how a CRC works, there is one important concept that we need to understand first: The endianness.

Endianness

The endianness is the order of bytes with which data words are stored. We distinguish the following to types:

  • Little-endian: The least significant byte is stored at the smallest memory address. In terms of data transmission, the least significant byte is transmitted first.
  • Big-endian: The most significant byte is stored at the smallest memory address. In terms of data transmission, the most significant byte is transmitted first.


In the introductory example (with the letter z), we only used a CRC with a size of 1 byte, so the endianness doesn’t matter in this case. However, in many cases, we use CRCs that consist of mulitple bytes. So the question arises which endianness to use for CRC?

From an app developer’s perspective, the answer is quite simple: We use the same endianness as the system we want to communicate with. It’s usually required by the hardware to use a particular byte order. For the remainder of this article, we’ll stick with the big-endian format and provide some hints along the way on how a little-endian implementation would differ.

The Concept of a CRC

Mathematically spoken, a CRC is the remainder of a modulo-2 polynomial division of the data. So, the CRC can be written as

CRC = data %2 polynomial

The polynomial can be any mathematical polynomial (without any coefficients) up to the order of the CRC bit size. So if we want a CRC with 8 bits, the highest exponent of the polynomial must be 8 as well. Example:

x8 + x2 + x + 1

As you can imagine from the simple equation above, choosing a different polynomial will result in a different CRC for the same data. So sender and receiver need to agree on a common polynomial, or else they will always end up with a different CRC and assume that the data got corrupted on the way. Depending on the use case, some polynomials are better suited than others. (Picking the right one is a topic on its own and beyond the scope of this article.)

Any such polynomial can be represented in binary form by going through the exponents from highest to lowest and writing a 1 for each exponent that is present (8, 2, 1 and 0 in our example) and a 0 for each absent exponent (7, 6, 5, 4, 3 in this case):

Exponent    8 7 6 5 4 3 2 1 0
Polynomial  1 0 0 0 0 0 1 1 1 
–––––––––––––––––––––––––––––
Bit Index   0 1 2 3 4 5 6 7 8

The above is the big-endian representation of the polynomial. For its little-endian representation, simply reverse the order of bits:

Exponent    0 1 2 3 4 5 6 7 8
Polynomial  1 1 1 0 0 0 0 0 1 
–––––––––––––––––––––––––––––
Bit Index   0 1 2 3 4 5 6 7 8

Here are some example polynomials with their (big-endian) binary representation:

Polynomial Binary Representation
x4 + x2 + x + 1 10111
x4 + x3 + x2 + 1 11101
x8 + x4 + x2 + 1 100010101

Next, in order to be able to calculate a CRC, we need to understand the modulo-2 division.

Making Calculations in Modulo-2 Arithmetic

Modulo-2 arithmetic is performed digit by digit (bit by bit) on binary numbers. There is no carry or borrowing in this arithmetic. Each digit is considered independent from its neighbours.

Addition & Subtraction

The curious thing about modulo-2 arithmetic is that both addition and subtraction yield the same result.

  10          10
+ 11        - 11
-----       ------
  01          01

The sum or the difference of two bits can be computed with an XOR operation: The result is 1 if exactly one of the two bits is 1, otherwise the result is 0. As there is no carry or borrowing, the same applies not only for individual bits, but for binary numbers of any length, for example:

  10  +  11
= 10  -  11
= 10 XOR 11
= 01 

We get this result by applying the XOR operator on each pair of bits individually:

1 XOR 1 =  0
0 XOR 1 =  1
         -----
          01

Division

Modulo-2 division is performed similarly to “normal” arithmetic division. The only difference is that we use modulo-2 subtraction (XOR) instead of arithmetic subtraction for calculating the remainders in each step.

⚠️ If you are German, please note that in English literature, the divisor 11011 is written first, followed by the dividend 01111010. (In German literature it’s usually the other way around.) The result of the division (quotient) is written on top of the calculation, the remainder at the bottom.

       01011 ⬅︎ Quotient
      ––––––––––––––––––
11011 | 01111010
      - 00000
      ----------
         1111010
       - 11011
       ---------
          010110
        - 00000
        --------
           10110
         - 11011
         -------
            11010
          - 11011
          -------
            0001 ⬅︎ Remainder (mod-2)

Types of CRCs

There are different types of CRCs. They are categorized by the degree of the polynomial they use. As the first exponent of a polynomial of degree n is always present by definition (otherwise it would have a lower degree), its binary representation always begins with a 1. In other words, the first bit of a binary polynomial representation doesn’t carry any information about the polynomial when we agree on a fixed degree.

For that reason, the first bit of a binary polynomial representation is always dropped when computing a CRC in software. So the bit size of the resulting binary representation is always n for a polynomial of degree n. Example:

Polynomial Binary Representation Binary (1st bit dropped) Bit Size
x4 + x2 + x + 1 10111 0111 4
x4 + x3 + x2 + 1 11101 1101 4
x8 + x4 + x2 + 1 100010101 00010101 8

CRCs types are named by their bit size. Here are the most common ones:

  • CRC-8
  • CRC-16
  • CRC-32
  • CRC-64
  • CRC-1 (parity bit) is a special case

Generally, we can refer to a CRC as CRC-n, where n is the number of CRC bits and the number of bits of the polynomial’s binary representation with a dropped first bit. Obviously, different CRCs are possible for the same n as multiple polynomials exist for the same degree.

For example, if we want to calculate the CRC-8 for these bits:

01000001

the result looks different, depending on the polynomial we use:

Binary Polynomial (1st bit dropped) CRC-8
110100111 11001100
100000111 11000000
101001001 01100110
111010101 01001000

Above are the standard CRC-8 polynomials used in different applications such as Bluetooth, GSM-B, etc.

Error Detection

How do we choose a suitable CRC and a respective polynomial? There are three things we need to consider:

  1. Random Error Detection Accuracy
  2. Burst Error Detection Accuracy
  3. The Redundancy Factor

Random Error Detection Accuracy

Random errors are errors that can occur randomly in any data. For example, a single bit is flipped when transmitting data or a few bits are lost during the transmission.

Depending on the bit size of the CRC we use, we can detect most of these random errors. However, for a CRC-n, 1/2n of these errors cannot be detected. The following table shows the percentage of the possible random errors that remain undetected for each CRC type:

CRC Type Undetected Errors % Undetected
CRC-8 1/28 0.39
CRC-16 1/216 0.0015
CRC-32 1/232 0.00000002
CRC-64 1/264 5.4 x 10-20

Burst Error Detection Accuracy

Errors in data transmission are oftentimes not random but produced over a consecutive sequence of bits. Such errors are called burst errors. They are the most common errors in data communication.

It’s one of the CRC’s strongest properties to detecting burst errors reliably. A CRC-n can detect single burst errors with a maximum length of n bits. However, this depends a lot on the polynomial used for computing the CRC. Some polynomials are able to detect multiple bursts of errors in the transmitted data.

CRC Type Burst Error Detection
CRC-8 at least a single burst of <= 8 bits
CRC-16 at least a single burst of <= 16 bits
CRC-32 at least a single burst of <= 32 bits
CRC-64 at least a single burst of <= 64 bits

The Redundancy Factor

Using a CRC for error detection comes at the cost of extra (non-meaningful) data. When we use a CRC-32 (4 bytes), we need to transmit two more bytes of “unnecessary” data as compared to a CRC-16. CRCs with a lower bit size are obviously cheaper with respect to storage space.

Based on these three factors, we can decide which CRC type to choose for our application. However, the polynomial you choose for your CRC also affects the efficiency and quality of your error detection. But that’s a topic for itself and we won’t cover it in this article. Fortunately, there are a couple of standard polynomials used for a particular CRC type and in most cases it makes sense to just use one of these.

How It Works: The CRC Algorithm

This section will take you through the steps of calculating a CRC-n for any input data. We will first explain the algorithm and then follow these steps to calculate a 4-bit CRC of some sample data.

  1. Take the CRC polynomial and remove the most significant bit.
    Example: 100110011
  2. Append n zeros to the input.
    We call this input the remainder (as it will be the remainder of our binary division after every step and finally becomes the CRC when division is no longer possible).
  3. Remember the most significant bit.
    Example: 1010 ➔ most significant bit = 1
  4. Discard the most significant bit.
    Example: 1010010
  5. Depending on the most significant bit from step 3, do the following:
    • 0 do nothing (same as subtracting 0 from the remainder)
    • 1 ➔ subtract the divisor (polynomial) from the remainder
  6. Repeat steps 3 to 5 for all the bits of the message.
  7. The final remainder is the CRC.

Example

Let’s see how this algorithm works in practice and calculate the 4-bit CRC for the binary Unicode representation of the letter z (as introduced at the beginning of this article):

  • Input Data: 0111 1010

First, we need to choose a suitable polynomial depending on our use case which must used by both the sender and the receiver. For this example, let’s use this one:

Polynomial Binary Representation Binary (1st bit dropped) Bit Size
x4 + x3 + x + 1 11011 1011 4

We have already performed step (1) of the algorithm in the table above: 1011 is our binary polynomial representation with a dropped most significant bit. Next, let’s go through the remaining steps as part of our modulo-2 division:

       (Quotient is ignored)
       –––––––––––––––––––––
1011 | 01111010              // 1. Polynomial with dropped MSB | Input        
       01111010 0000         // 2. Append 4 zero bits for the CRC

       01111010 0000         // 3. MSB (first bit) = 0
       -------------
        1111010 0000         // 4. Discard the MSB
      - 0000                 // 5. Do nothing (= subtract 0000)
       ––––––––––––––––––
        1111010 0000         // 3. MSB = 1
        ------------
         111010 0000         // 4. Discard the MSB    
       - 1011                // 5. Subtract the polynomial
       ––––––––––––––––––
         010110 0000         // 3. MSB = 0
         -----------
          10110 0000         // 4. Discard the MSB
        - 0000               // 5. Do nothing (= subtract 0000)
       ––––––––––––––––––
          10110 0000         // 3. MSB = 1
          ----------
           0110 0000         // 4. Discard the MSB
         - 1011              // 5. Subtract the polynomial
       ––––––––––––––––––
           1101 0000         // 3. MSB = 1
           ----------
            1010000          // 4. Discard the MSB
          - 1011             // 5. Subtract the polynomial
       ––––––––––––––––––
             0001000         // 3. MSB = 0
             -------
              001000         // 4. Discard the MSB
            - 0000           // 5. Do nothing (= subtract 0000)
       ––––––––––––––––––
              001000         // 3. Check the most significant bit (MSB = 0)
              ------
               01000         // 4. Discard the MSB
             - 0000          // 5. Do nothing (= subtract 0000)
       ––––––––––––––––––
               01000         // 3. MSB = 0
               -----
                1000         // 4. Discard the MSB
              - 0000         // 5.Do nothing (= subtract 0000)
       ––––––––––––––––––
                1000         // 7. Final remainder = CRC

Implementing The Algorithm in Software

Once you’ve understood the algorithm above, it’s pretty straight-forward to implement it in software. The only thing you need to be clear about is whether you implement the CRC with a big-endian or a little-endian representation. In the following, we’ll provide some concrete implementation advice, assuming a big-endian format.

  1. Take the CRC polynomial and remove the most significant bit.
    Usually, you do this manually as you only need to do it once.
    (For little-endian: Reverse the bits of the resulting value.)
  2. Append n zeros to the input.
    Not needed in software.
  3. Remember the most significant bit.
    This is equivalent to performing an AND operation with a value that has a 1 as its most significant bit and a 0 in every other bit. (For little-endian: Just do AND 1, regardless of the CRC size.)
    Store this value in a variable. Example:
    • 8 bits ➔ 1000 00000x80
    • 16 bits ➔ 1000 0000 0000 00000x800
    • 32 bits ➔ 1000 0000 0000 00000000 0000 0000 00000x8000000
  4. Discard the most significant bit.
    This is equivalent to performing a bitwise left-shift.
    (For little-endian: Do a bitwise right-shift.)
  5. Depending on the value of the variable stored in step (3), do the following:
    • 0 ➔ do nothing
    • 1 ➔ perform and XOR operation with the remainder and the polynomial
  6. Repeat Steps 3 to 5 for all the bits of the message.
    A simple for loop or any functional construct (e.g. reduce in Swift, fold in Kotlin) will do the job.
  7. The final remainder is the CRC.
    That’s the same in software, of course.

The concrete implementation of a CRC algorithm in software always depends on the platform and the programming language you use. If you know how to work with bits and bytes on your respective platform, you should now be able to implement a CRC algorithm of your desired type on your own.

However, if you are an iOS or macOS developer and don’t want to out in all the effort to write your own implementation from scratch, we’ve dedicated another article for implementing a CRC with Swift on iOS. Another article for Android developers on how to implement a CRC in Kotlin is in our pipeline and coming soon. Stay tuned!

Summary

Congratulations! You’ve made it to the end of this article and should now have a broad understanding of what a Cyclic Redundancy Check (CRC) is and how it works. Here’s a short summary of this article:

  • CRCs are codes that help us in detecting unintended errors in any transmitted or stored data.
  • Burst errors are very common in data communication.
  • A CRC-n can detect burst errors up to a size of n bits.
  • Since the order of the bytes matters when calculating CRC, it can also detect when the sequence of bytes has changed.
  • Using a different polynomial for a CRC algorithm will result in a different CRC for the same data.
  • Endianness matters! Using the same polynomial with the opposite endianness will result in a completely different CRC.

Let us finish with some final thoughts on things you should be aware of:

  • CRC implementations can be made more efficient by pre-calculating a so-called CRC lookup tables. Please check our other CRC articles to see example implementations that make use of such a lookup table.
  • A CRC is only meant to detect unintended errors or changes to data. It does not provide any protection against malicious changes. If you want to make your data communication secure, you need to use cryptography instead. (A possible attacker can always recalculate the CRC after changing the data.) We’ve published a couple of articles on that topic as well (see below). 😉

Where to Go From Here

  • If your company needs a team to help you implement CRCs or to develop an app with Bluetooth capabilities, reach out to us at: [email protected]
  • If you are curious and would like to see a concrete implementation of a CRC algorithm, we’ve got you covered with two other articles:
    • Data Integrity: CRC with Swift on iOS
    • Data Integrity: CRC with Kotlin on Android
  • You can also check out our GitHub repository with some sample implementations of CRC functions in Swift.
  • If you’re not only interested in detecting accidental data transmission errors, but want to make sure that no one else can read or tamper with your sensitive data, read our articles on app security:
    • Mobile App Security: Best Practices on Android & iOS
    • iOS App Security: Best Practices
    • Android App Security: Best Practices

Are you a Software Developer?
Do you want to work with people that care about good software engineering?
Join our team in Munich

Body

Troubleshooting CRC Errors On Storage Networks

   

Before I say anything else, I will say that there is no «Easy Button» for troubleshooting CRC errors. It is an iterative process. You make a change, you monitor your fabric, and if necessary you make more changes until the issues are resolved. I frequently have customers who want it to be a one step process. It can be, but usually takes multiple steps. Having said that, before we can fix them, we need to know what CRC errors are and why they occur.

What Are CRC Errors? When Do they Occur?

The simple answer is that CRC errors are damaged frames. The more complicated answer is that before a fibre-channel frame is sent, some math is done. The answer is added to the frame footer. When the receiver gets the frame, the receiver repeats the math. If the receiver gets a different answer then what’s recorded in the frame, then the frame was changed in flight. This is a CRC error. The only time these happen is if the physical plant — cabling, SFPs is somehow defective. It is much less common, but still possible to have a bad component in the switch. Troubleshooting that will be a separate blog post, some day. What the receiver does with the damaged frame depends on whether it’s a switch or end device and if it is a switch, what brand of switch.

Why Does Fixing These Matter?

At best, the effect of faulty links is a few dropped frames. Left unchecked the problem will get worse and eventually cause performance problems. Also, you will go from 1 or 2 bad links to many. A customer I have been working with for the last several months was in this situation and is finally finishing a very long process of cleaning up many faulty links. Years ago I had customer that was experiencing extremely long delays on their Brocade fabric. They had over-redundancy (there is such a thing) on the switches and links between the hosts and the storage. Many of the links were questionable and producing CRC errors. When the storage received a bad frame, it simply dropped it and did not send an ABTS. They also had an adapter in the host with a bug in it, and it would simply sit and wait for the storage to respond. 90 or so seconds later, the application would time out and initiate recovery for a problem that should never have happened.

Why Does It Matter What Brand Of Switch It Is?

First, the different brands of switches use different commands to obtain the data you need to troubleshoot these problems. Secondly the way that they check and forward frames is different. This requires a different technique depending on the brand of switch. Cisco switches are what is called store-and-forward. This means that they wait for the entire frame to be received, then they check it, then if the frame is valid it gets forwarded. If not, it is dropped. Brocade switches are cut-through. As soon as they receive enough of the frame to know where it’s going, they start forwarding it. If the frame ends up being bad, they try to correct it using Foward Error Correction. If that doesn’t work the frame is tagged as bad. For the most part, end devices that receive frames that are already tagged as bad simply drop the frame and initiate recovery via ABTS. Troubleshooting commands and techniques vary for Brocade vs Cisco fabrics.

Identifying CRCs on Cisco Fabrics

Since Cisco fabrics are store-and-forward, you know that frames with CRC errors will be dropped as soon as they are detected. This can be either at the switch port they arrive on, or more rarely inside the switch. This post will focus on the CRC errors detected at the switch ports. If you suspect that you have questionable links, you can use these commands to check switch ports for CRC errors:

  • ‘show interface’
  • ‘show interface counters’
  • ‘show logging log

For the above — the ‘show interface’ and ‘show interface counters’ commands can be run specifying a switch port that you are interested in. this is done in the format of fcS/P where S is the slot and P is the port. For the ‘show logging log’ you are looking for messages that a port was disabled because the bit error rate was too high. This is often an indicator of a faulty link. Once you find the ports that are detecting the CRC errors, you can then proceed to the repair phase.

Identifying CRCs on Brocade Fabrics

Brocade fabrics use cut-through routing. As such, the link for the port that is detecting the CRC errors may not be the faulty link. Brocade has two statistics for CRCs: CRC and CRC_Good_EOF. If the CRC_Good_EOF counter is increasing, this means that the link it is increasing on is the source of the problem. If the CRC counter is increasing, then the frame has already been marked as bad, and the problem is occuring elsewhere on the SAN. The CRC_Good_EOF should be the only counter that increases on a device port. If the CRC_Good_EOF counter is increasing on an ISL port, the link between the sending and receiving switch is bad. If you the CRC counter is increasing on the ISL, this means the problem is occuring somewhere on the sending switch. So move to the sending switch and look for ports where CRC_Good_EOF is increasing. It is possible that both counters will increase on a link. If it is a device port, then the link is bad. If it is an ISL then the link itself is a problem, and the sending switch has other bad links attached to it.    As you can see there are a few more steps to identify the source of the CRC errors on Brocade before you can proceed to the repair phase.  The porterrshow may also show ports that do not have CRC_Good_EOF increasing, but do show a counter called PCS increasing. If so, this is also and indication of a bad link. Troubleshooting PCS errors is the same as troubleshooting CRC_Good_EOF errors.

  • ‘porterrshow’
  • ‘portstatsshow N’

The porterrshow command will display error stats for all ports. The portstatsshow N where N is a port index number will display more detailed stats for the specified port. If you see PCS errors increasing for a port in the porterrshow, the link oin that port is bad, regardless of what CRC or CRC_Good_EOF counters there are.

Correcting the Problem

Once you have identified the port(s) that have questionable links you need to correct the problem. As I mentioned earlier, this is an iterative process. You replace a part, then clear the switch statistics, then monitor for anywhere from several hours to a day, depending on the rate of increase. Repeat the process until the errors are no longer increasing. You can replace multiple parts at once — such as replacing a cable and an SFP at the same time. Another option is to isolate further by just swapping a cable, or moving the device to a new port on the switch. Just remember that it is critical to reset the statistics immediately after any change you make.  REMEMBER THAT PATCH PANELS  ARE PART OF CABLING.  I emphasize that because customers will often replace the cable between the switch/device and the panel and forget that there is cabling between patch panels which is also suspect.  Some years ago I went onside to to troubleshoot connectivity between two storage systems.  The storage systems were located  at different campuses in the same city. The replication paths would not stay up.   When I got there, the client had them direct connected through several patch panels with no switching.  I assisted them in putting the cabling through switches at each campus and immediately saw CRCs showing up on the links.  They had 8 hops across patch panels between the storage systems.  We found CRCs at the second hop at each side. I stopped checking after that.  Their eventual permanent fix was to run a new direct run of cable between the two locations

If you have any questions, leave them in the comments or find me on   LinkedIn or on Twitter.

[{«Business Unit»:{«code»:»BU054″,»label»:»Systems w/TPS»},»Product»:{«code»:»HW206″,»label»:»Storage Systems»},»Component»:»»,»Platform»:[{«code»:»PF025″,»label»:»Platform Independent»}],»Version»:»»,»Edition»:»»,»Line of Business»:{«code»:»LOB26″,»label»:»Storage»}}]

Понравилась статья? Поделить с друзьями:
  • Code 9999 message undefined command xvacuum firmware ошибка
  • Code 9907 genshin impact как исправить на телефоне
  • Code 800b0100 windows 7 update error
  • Code 80072efd windows update error
  • Code 643 windows update error