comm.CRCDetector
Detect errors in input data using CRC
Description
The comm.CRCDetector
System object™ computes cyclic redundancy check (CRC) checksums for an entire received
codeword. For successful CRC detection in a communications system link, you must align the
property settings of the comm.CRCDetector
System object with the paired comm.CRCGenerator
System object. For more information, see CRC Syndrome Detector Operation.
To detect errors in the received codeword containing CRC sequence bits:
-
Create the
comm.CRCDetector
object and set its properties. -
Call the object with arguments, as if it were a function.
To learn more about how System objects work, see What
Are System Objects?
Creation
Syntax
Description
creates a CRCcrcdetector
= comm.CRCDetector
code detector System object. This object detects errors in the received codewords according to a
specified generator polynomial.
example
crcdetector
= comm.CRCDetector(Name
,Value
)
sets properties using one or more name-value pairs. For example,
comm.CRCDetector('Polynomial','z^16 + z^14 + z + 1')
configures the
CRC code detector System object to use the CRC-16 cyclic redundancy check bits when checking for CRC code
errors in the received codewords. Enclose each property name in quotes.
crcdetector
= comm.CRCDetector(poly,Name
,Value
)
creates a CRC code detector System object. This object has the Polynomial
property
set to poly
, and the other specified properties set to the specified
values.
Properties
expand all
Unless otherwise indicated, properties are nontunable, which means you cannot change their
values after calling the object. Objects lock when you call them, and the
release
function unlocks them.
If a property is tunable, you can change its value at
any time.
For more information on changing property values, see
System Design in MATLAB Using System Objects.
Polynomial
— Generator polynomial
'z^16 + z^12 + z^5 + 1'
(default) | polynomial character vector | binary row vector | integer row vector
Generator polynomial for the CRC algorithm, specified as one of the
following:
-
A polynomial character vector such as
'z^3 + z^2 + 1'
. -
A binary row vector that represents the coefficients of the generator polynomial
in order of descending power. The length of this vector is (N+1),
where N is the degree of the generator polynomial. For example,
[1 1 0 1]
represents the polynomial
x3+
z2+ 1. -
An integer row vector containing the exponents of z for the
nonzero terms in the polynomial in descending order. For example,[3 2
represents the polynomial z3
0]
+ z2 + 1.
For more information, see Representation of Polynomials in Communications Toolbox.
Some commonly used generator polynomials include:
CRC method | Generator polynomial |
---|---|
CRC-32 | 'z^32 + z^26 + z^23 + z^22 + z^16 + z^12 + z^11 + z^10 + z^8 + z^7 + z^5 + z^4 + z^2 + z + 1' |
CRC-24 | 'z^24 + z^23 + z^14 + z^12 + z^8 + 1' |
CRC-16 | 'z^16 + z^15 + z^2 + 1' |
Reversed CRC-16 | 'z^16 + z^14 + z + 1' |
CRC-8 | 'z^8 + z^7 + z^6 + z^4 + z^2 + 1' |
CRC-4 | 'z^4 + z^3 + z^2 + z + 1' |
Example: 'z^7 + z^2 + 1'
, [1 0 0 0 0 1 0 1]
,
and [7 2 0]
represent the same polynomial,
p(z) = z
7 + z
2 + 1.
Data Types: double
| char
InitialConditions
— Initial states of internal shift register
0
(default) | 1
| binary row vector
Initial states of the internal shift register, specified as a binary scalar or a
binary row vector with a length equal to the degree of the generator polynomial. A
scalar value is expanded to a row vector of equal length to the degree of the generator
polynomial.
Data Types: logical
DirectMethod
— Use direct algorithm for CRC checksum calculations
false
(default) | true
Use direct algorithm for CRC checksum calculations, specified as
false
or true
.
When you set this property to true
, the object uses the direct
algorithm for CRC checksum calculations. When you set this property to
false
, the object uses the non-direct algorithm for CRC checksum
calculations.
For more information on direct and non-direct algorithms, see Error Detection and Correction.
Data Types: logical
ReflectInputBytes
— Reflect input bytes
false
(default) | true
Reflect input bytes, specified as false
or
true
. Set this property to true
to flip the
received codeword on a bytewise basis before entering the data into the shift
register.
When you set this property to true
, the received codeword length
divided by the value of the ChecksumsPerFrame
property must be an integer and a multiple of 8
.
Data Types: logical
ReflectChecksums
— Reflect checksums before final XOR
false
(default) | true
Reflect checksums before final XOR, specified as false
or
true
. Set this property to true
to flip the CRC
checksums around their centers after the received codeword is completely through the
shift register.
When you set this property to true
, the object flips the CRC
checksums around their centers before the final XOR.
Data Types: logical
FinalXOR
— Final XOR
0 (default) | binary scalar | binary vector
Final XOR, specified as a binary scalar or a binary row vector with a length equal
to the degree of the generator polynomial. The XOR operation runs using the value of the
FinalXOR
property and the CRC checksum before comparing with the
input checksum. A scalar value is expanded to a row vector of equal length to the degree
of the generator polynomial. A setting of 0
is equivalent to no XOR
operation.
Data Types: logical
ChecksumsPerFrame
— Number of checksums calculated
1 (default) | positive integer
Number of checksums calculated for each received codeword frame, specified as a
positive integer. for more information, see CRC Syndrome Detector Operation.
Data Types: double
Usage
Syntax
Description
example
out
= crcdetector(codeword
)
checks CRC code bits for each received codeword frame, removes the checksums, and then
concatenates subframes to the output frame.
example
[msg,err]
= crcdetector(codeword
)
also returns the checksum error signal computed when checking CRC code bits for each
codeword subframe.
Input Arguments
expand all
codeword
— Received codeword
binary column vector
Received codeword, specified as a binary column vector.
Data Types: double
| logical
Output Arguments
expand all
out
— Output frame
binary column vector
Output frame, returned as a binary column vector that inherits the data type of
the input signal. The message word output contains the received codeword with the
checksums removed.
The length of the output frame is n — k *
r bits, where n is the size of the received
codeword, k is the number of checksums per frame, and
r is the degree of the generator polynomial.
err
— Checksum error signal
binary column vector
Checksum error signal, returned as a binary column vector that inherits the data
type of the input signal. The length of Err
equals the value of
ChecksumsPerFrame
. For each checksum computation, an element
value of 0 in err
indicates no checksum error, and an element
value of 1 in err
indicates a checksum error.
Object Functions
To use an object function, specify the
System object as the first input argument. For
example, to release system resources of a System object named obj
, use
this syntax:
expand all
Common to All System Objects
step |
Run System object algorithm |
release |
Release resources and allow changes to System object property values and input characteristics |
reset |
Reset internal states of System object |
Examples
collapse all
CRC Detection of Errors in a Random Message
Pass binary data through a CRC generator, introduce a bit error, and detect the error using a CRC detector.
Create a random binary vector.
Encode the input message frame using a CRC generator with the ChecksumsPerFrame
property set to 2
. This subdivides the incoming frame into two equal-length subframes.
crcgenerator = comm.CRCGenerator([1 0 0 1],'ChecksumsPerFrame',2);
codeword = crcgenerator(x);
Decode the codeword and verify that there are no errors in either subframe.
crcdetector = comm.CRCDetector([1 0 0 1],'ChecksumsPerFrame',2);
[~, err] = crcdetector(codeword)
Introduce an error in the second subframe by inverting the last element of subframe 2. Pass the corrupted codeword through the CRC detector and verify that the error is detected in the second subframe.
codeword(end) = not(codeword(end)); [~,err] = crcdetector(codeword)
Cyclic Redundancy Check of Noisy BPSK Data Frames
Use a CRC code to detect frame errors in a noisy BPSK signal.
Create a CRC generator and detector pair using a standard CRC-4 polynomial, z4+z3+z2+z+1.
poly = 'z4+z3+z2+z+1';
crcgenerator = comm.CRCGenerator(poly);
crcdetector = comm.CRCDetector(poly);
Generate 12-bit frames of binary data and append the CRC bits. Based on the degree of the polynomial, 4 bits are appended to each frame. Apply BPSK modulation and pass the signal through an AWGN channel. Demodulate and use the CRC detector to determine if the frame is in error.
numFrames = 20; frmError = zeros(numFrames,1); for k = 1:numFrames data = randi([0 1],12,1); % Generate binary data encData = crcgenerator(data); % Append CRC bits modData = pskmod(encData,2); % BPSK modulate rxSig = awgn(modData,5); % AWGN channel, SNR = 5 dB demodData = pskdemod(rxSig,2); % BPSK demodulate [~,frmError(k)] = crcdetector(demodData); % Detect CRC errors end
Identify the frames in which CRC code bit errors are detected.
More About
expand all
Cyclic Redundancy Check Coding
Cyclic redundancy check (CRC) coding is an error-control coding technique for
detecting errors that occur when a data frame is transmitted. Unlike block or convolutional
codes, CRC codes do not have a built-in error-correction capability. Instead, when a
communications system detects an error in a received codeword, the receiver requests the
sender to retransmit the codeword.
In CRC coding, the transmitter applies a rule to each data frame to create extra CRC bits,
called the checksum or syndrome, and then appends the checksum to the data frame. After receiving a
transmitted codeword, the receiver applies the same rule to the received codeword. If the
resulting checksum is nonzero, an error has occurred and the transmitter should resend the
data frame.
When the number of checksums per frame is greater than 1, the input data frame is divided
into subframes, the rule is applied to each data subframe, and individual checksums are
appended to each subframe. The subframe codewords are concatenated to output one
frame.
For a discussion of the supported CRC algorithms, see Cyclic Redundancy Check Codes.
CRC Syndrome Detector Operation
The CRC syndrome detector outputs the received message frame and a checksum
error vector according to the specified generator polynomial and number of checksums per
frame.
The checksum bits are removed from each subframe, so that the resulting
the output frame length is n — k ×
r, where n is the size of the received codeword,
k is the number of checksums per frame, and r is
the degree of the generator polynomial. The input frame must be evenly divisible by
k.
For a specific initial state of the internal shift register:
-
The received codeword is divided into k equal sized
subframes. -
The CRC is removed from each of the k subframes and compared to
the checksum calculated on the received codeword subframes. -
The output frame is assembled by concatenating the subframe bits of the
k subframes and then output as a column vector. -
The checksum error is output as a binary column vector of length
k. An element value of 0 indicates an error-free received
subframe, and an element value of 1 indicates an error occurred in the received
subframe.
For the scenario shown here, a 16-bit codeword is received, a third degree generator
polynomial computes the CRC checksum, the initial state is 0, and the number of checksums
per frame is 2.
Since the number of checksums per frame is 2 and the generator polynomial degree is 3, the
received codeword is split in half and two checksums of size 3 are computed, one for each
half of the received codeword. The initial states are not shown, because an initial state of
[0]
does not affect the output of the CRC algorithm. The output frame
contains the concatenation of the two halves of the received codeword as a single vector of
size 10. The checksum error signal output contains a 2-by-1 binary frame vector whose
entries depend on whether the computed checksums are zero. As shown in the figure, the first
checksum is nonzero and the second checksum is zero, indicating an error occurred in
reception of the first half of the codeword.
References
[1] Sklar, Bernard. Digital
Communications: Fundamentals and Applications. Englewood Cliffs, N.J.:
Prentice-Hall, 1988.
[2] Wicker, Stephen B.
Error Control Systems for Digital Communication and Storage. Upper
Saddle River, N.J.: Prentice Hall, 1995.
Extended Capabilities
Ошибка в данных CRC может возникнуть в самых разных случаях: при инициализации жесткого диска или работе с внешним жестким диском, картой памяти или флешкой, попытках произвести действия с накопителем в DISKPART, часто — при установке программ и игр, скачанных с торрента.
Текст ошибки также может быть разным: от простого сообщения диспетчера виртуальных дисков об ошибке в данных при инициализации диска, сообщений «DISKPART обнаружила ошибку: Ошибка в данных (CRC)» или «Расположение недоступно. Нет доступа к диску, ошибка данных (CRC)» при действиях с HDD, картой памяти или USB накопителем, до окон вида «CRC error» или «Ошибка копирования файла» с указанием на файлы устанавливаемого ПО. В этой инструкции подробно о причинах такой ошибки, что она означает и о возможных методах её исправить.
- Что такое 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 для диска нет и иногда мы имеем дело с его аппаратной неисправностью. Среди возможных способов решения проблемы:
- Если на компьютере или ноутбуке ранее любым способом включался разгон памяти или процессора, отключите его. Если в последнее время менялась конфигурация, например, добавлялись модули RAM, верните исходную конфигурацию и посмотрите, не приведёт ли это к исчезновению ошибки.
- Проверьте работу, загрузив Windows в безопасном режиме (Как зайти в безопасный режим Windows 10). При загрузке в безопасном режиме встроенный антивирус Windows 10 и 8.1 не запускается. Если при наличии стороннего антивируса он запустился — временно отключите и его. Проверьте, сохраняется ли ошибка. Если ошибка CRC не возникает, ошибка может быть как в антивирусе (более вероятно), так и в сторонних службах и фоновых программах из автозагрузки (которые также не запускаются в безопасном режиме).
- Следующее действие лучше всего выполнять, не выходя из безопасного режима. Если диск с ошибкой инициализирован и ему присвоена буква, запустите командную строку от имени администратора и введите следующую команду, заменив букву диска D на свою (подробнее: Проверка жесткого диска на ошибки).
chkdsk D: /f /r
Выполнение команды может занять очень продолжительное время, не выполняйте при питании от батареи на ноутбуке.
- Если недавно проблема не возникала, попробуйте использовать точки восстановления системы на случай, если ошибка вызвана проблемами с конфигурацией ОС в реестре.
- Для внешнего USB диска и флешки — используйте разъёмы на задней панели ПК и не используйте USB-хабы (разветвители портов), попробуйте использовать разъем USB 3.0 вместо 2.0 или наоборот. При наличии дополнительных кабелей для подключения дисков, проверьте их в работе.
- Если конструкция внешнего диска позволяет его разобрать и извлечь накопитель — сделайте это и проверьте работу накопителя при прямом подключении к компьютеру кабелем SATA (не забывая про кабель питания).
- Для SATA жестких дисков — попробуйте использовать другой кабель для подключения. При отсутствии свободных кабелей можно использовать необязательный, например, от привода оптических дисков.
- Если у вас ПК и к нему подключено большое количество жестких дисков и/или SSD, временно отключите все необязательные и проверьте, повлияет ли это действие на ситуацию.
- Для SSD — установите официальную утилиту от производителя для вашей модели накопителя: возможно, в ней будет информация о неисправности, иногда — возможность обновить прошивку (возможно, не стоит выполнять), про такие программы: Программы для SSD дисков.
Внимание: при рассматриваемой ошибке обновление прошивки может привести и к полной неработоспособности диска.
- Если данные на накопителе не представляют ценности, вы можете: для жестких дисков и SSD попробовать выполнить форматирование средствами системы, для карт памяти и USB накопителей, можно попробовать выполнить форматирование в Windows, в других устройствах (смартфоны, фотоаппараты) использовать специальные программы для ремонта флешки.
Одно из решений должно позволить исправить ошибку в данных CRC, при условии, что мы не имеем дело с аппаратной неисправностью диска. Если к настоящему моменту времени работа диска не была проверена на другом компьютере — найдите возможность сделать это, а при сохранении проблемы от использования накопителя придется отказаться.
Если диск содержит важные данные и инициализируется в системе, вы можете использовать бесплатные программы для восстановления данных (с большой вероятностью подойдет DMDE в режиме просмотра содержимого томов), если не инициализируется — останется обратиться в специализированную лабораторию для восстановления.
Ошибка возникает при установке игр и программ или при их запуске
В случае, если ошибка в данных CRC появляется при попытках установить или запустить какое-либо программное обеспечение, возможными вариантами решения будут:
- Отключение вашего антивируса, повторная загрузка установщика игры или программы, добавление папки с установщиком и папки, куда производится установка в исключения антивируса, запуск установки.
- Загрузка установщика из другого источника.
- В случае если не запускается программа, которая раньше работала — использование точек восстановления системы при их наличии, переустановка программы.
- Отключение разгона оперативной памяти и процессора, отключение утилит для очистки оперативной памяти при их наличии.
- Проверка жесткого диска на ошибки командой из 3-го шага предыдущего раздела.
- Загрузка установщика программы на другой физический диск, если на компьютере их более одного.
- В случае недавнего изменения аппаратной конфигурации компьютера, добавления или замены RAM, попробуйте вернуть исходную конфигурацию и проверить, сохраняется ли ошибка.
- В редких случаях причиной проблемы могут быть символы кириллицы в пути к файлу установщика или в пути к месту установки: проверьте, сохранится ли ошибка если исключить кириллицу в именах папок и полных путей к этим расположениям.
И, в завершение, если один из способов помог в исправлении ошибки в данных CRC, буду благодарен вашему комментарию с описанием ситуации и решения: это поможет составить статистику, которая будет полезной другим читателям.
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 − 2−n).
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]
where depends on the length of
and
. This can be also stated as follows, where
,
and
have the same length
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 is the degree of the primitive generator polynomial, then the maximal total block length is
, 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
, where
is a primitive polynomial of degree
, then the maximal total block length is
, and the code is able to detect single, double, triple and any odd number of errors.
A polynomial 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
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 may be transcribed as:
In the table below they are shown as:
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 . 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 | ||||||||||||||||
CRC-3-GSM | mobile networks[24] | 0x3 | 0x6 | 0x5 | 0x5 | odd | yes [25] | – | – | – | – | – | – | – | – | – | – | – | – | – | 4 | ∞ |
CRC-4-ITU | ITU-T G.704, p. 12 | 0x3 | 0xC | 0x9 | 0x9 | odd | ||||||||||||||||
CRC-5-EPC | Gen 2 RFID[26] | 0x09 | 0x12 | 0x05 | 0x14 | odd | ||||||||||||||||
CRC-5-ITU | ITU-T G.704, p. 9 | 0x15 | 0x15 | 0x0B | 0x1A | even | ||||||||||||||||
CRC-5-USB | USB token packets | 0x05 | 0x14 | 0x09 | 0x12 | odd | ||||||||||||||||
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 | ∞ |
CRC-6-ITU | ITU-T G.704, p. 3 | 0x03 | 0x30 | 0x21 | 0x21 | odd | ||||||||||||||||
CRC-7 | telecom systems, ITU-T G.707, ITU-T G.832, MMC, SD | 0x09 | 0x48 | 0x11 | 0x44 | odd | ||||||||||||||||
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 | ∞ |
CRC-8-AUTOSAR | automotive integration,[33] OpenSafety[34] | 0x2F | 0xF4 | 0xE9 | 0x97[12] | even | yes [32] | – | – | – | – | – | – | – | – | – | – | 3 | 3 | 119 | 119 | ∞ |
CRC-8-Bluetooth | wireless connectivity[35] | 0xA7 | 0xE5 | 0xCB | 0xD3 | even | ||||||||||||||||
CRC-8-CCITT | ITU-T I.432.1 (02/99); ATM HEC, ISDN HEC and cell delineation, SMBus PEC | 0x07 | 0xE0 | 0xC1 | 0x83 | even | ||||||||||||||||
CRC-8-Dallas/Maxim | 1-Wire bus[36] | 0x31 | 0x8C | 0x19 | 0x98 | even | ||||||||||||||||
CRC-8-DARC | Data Radio Channel[28] | 0x39 | 0x9C | 0x39 | 0x9C | odd | ||||||||||||||||
CRC-8-GSM-B | mobile networks[24] | 0x49 | 0x92 | 0x25 | 0xA4 | even | ||||||||||||||||
CRC-8-SAE J1850 | AES3; OBD | 0x1D | 0xB8 | 0x71 | 0x8E | odd | ||||||||||||||||
CRC-8-WCDMA | mobile networks[27][37] | 0x9B | 0xD9 | 0xB3 | 0xCD[12] | even | ||||||||||||||||
CRC-10 | ATM; ITU-T I.610 | 0x233 | 0x331 | 0x263 | 0x319 | even | ||||||||||||||||
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 | ||||||||||||||||
CRC-12 | telecom systems[39][40] | 0x80F | 0xF01 | 0xE03 | 0xC07[12] | even | ||||||||||||||||
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 | ||||||||||||||||
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 | |||||||||||||||||
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 | ||||||||||||||||
CRC-16-CDMA2000 | mobile networks[27] | 0xC867 | 0xE613 | 0xCC27 | 0xE433 | odd | ||||||||||||||||
CRC-16-DECT | cordless telephones[47] | 0x0589 | 0x91A0 | 0x2341 | 0x82C4 | even | ||||||||||||||||
CRC-16-T10-DIF | SCSI DIF | 0x8BB7[48] | 0xEDD1 | 0xDBA3 | 0xC5DB | odd | ||||||||||||||||
CRC-16-DNP | DNP, IEC 870, M-Bus | 0x3D65 | 0xA6BC | 0x4D79 | 0x9EB2 | even | ||||||||||||||||
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 | ||||||||||||||||
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 | ||||||||||||||||
CRC-24-Radix-64 | OpenPGP, RTCM104v3 | 0x864CFB | 0xDF3261 | 0xBE64C3 | 0xC3267D | even | ||||||||||||||||
CRC-24-WCDMA | Used in OS-9 RTOS. Residue = 0x800FE3.[51] | 0x800063 | 0xC60001 | 0x8C0003 | 0xC00031 | even | yes[52] | – | – | – | – | – | – | – | – | – | – | 4 | 4 | 8388583 | 8388583 | ∞ |
CRC-30 | CDMA | 0x2030B9C7 | 0x38E74301 | 0x31CE8603 | 0x30185CE3 | even | ||||||||||||||||
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 | ∞ |
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 | – | ∞ |
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 | – | ∞ |
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 | ||||||||||||||||
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 | ||||||||||||||||
CRC-64-ECMA | ECMA-182 p. 51, XZ Utils | 0x42F0E1EBA9EA3693 | 0xC96C5795D7870F42 | 0x92D8AF2BAF0E1E85 | 0xA17870F5D4F51B49 | even | ||||||||||||||||
CRC-64-ISO | ISO 3309 (HDLC), Swiss-Prot/TrEMBL; considered weak for hashing[59] | 0x000000000000001B | 0xD800000000000000 | 0xB000000000000001 | 0x800000000000000D | odd | ||||||||||||||||
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]
- ^ «An Algorithm for Error Correcting Cyclic Redundance Checks». drdobbs.com. Archived from the original on 20 July 2017. Retrieved 28 June 2017.
- ^ 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.
- ^ 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.
- ^ 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.
- ^ 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.
- ^ «algorithm design — Why is CRC said to be linear?». Cryptography Stack Exchange. Retrieved 5 May 2019.
- ^ 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.
- ^ «[MS-ABS]: 32-Bit CRC Algorithm». msdn.microsoft.com. Archived from the original on 7 November 2017. Retrieved 4 November 2017.
- ^ 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.
- ^ 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.
- ^ 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.
- ^ 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.
- ^ a b Cook, Greg (15 August 2020). «Catalogue of parametrised CRC algorithms». Archived from the original on 1 August 2020. Retrieved 18 September 2020.
- ^ 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.
- ^ 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.
- ^ Koopman, Philip (21 January 2016). «Best CRC Polynomials». Carnegie Mellon University. Archived from the original on 20 January 2016. Retrieved 26 January 2016.
- ^ 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.
- ^ 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.
- ^ 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.
- ^ 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.
- ^ a b «32 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 19 March 2018. Retrieved 5 November 2017.
- ^ 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
- ^ is always achieved for arbitrarily long messages
- ^ 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.
- ^ «3 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
- ^ 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)
- ^ 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.
- ^ 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.
- ^ «6 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
- ^ 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.
- ^ «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.
- ^ a b «8 Bit CRC Zoo». users.ece.cmu.edu. Archived from the original on 7 April 2018. Retrieved 19 January 2018.
- ^ «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.
- ^ 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.
- ^ «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.
- ^ Whitfield, Harry (24 April 2001). «XFCNs for Cyclic Redundancy Check Calculations». Archived from the original on 25 May 2005.
- ^ Richardson, Andrew (17 March 2005). WCDMA Handbook. Cambridge University Press. p. 223. ISBN 978-0-521-82815-4.
- ^ a b FlexRay Protocol Specification. 3.0.1. Flexray Consortium. October 2010. p. 114. (4.2.8 Header CRC (11 bits))
- ^ Perez, A. (1983). «Byte-Wise CRC Calculations». IEEE Micro. 3 (3): 40–50. doi:10.1109/MM.1983.291120. S2CID 206471618.
- ^ 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.
- ^ «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.
- ^ 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.
- ^ 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.
- ^ «Cyclic redundancy check (CRC) in CAN frames». CAN in Automation. Archived from the original on 1 February 2016. Retrieved 26 January 2016.
- ^ «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.
- ^ 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.
- ^ «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.
- ^ 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.
- ^ «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.
- ^ 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)
- ^ «OS-9 Operating System System Programmer’s Manual». www.roug.org. Archived from the original on 17 July 2018. Retrieved 17 July 2018.
- ^ 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.
- ^ «cksum». pubs.opengroup.org. Archived from the original on 18 July 2018. Retrieved 27 June 2017.
- ^ 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.
- ^ 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.
- ^ ETSI TS 100 909 Archived 17 April 2018 at the Wayback Machine version 8.9.0 (January 2005), Section 4.1.2 a
- ^ 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)
- ^ 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.
- ^ 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
Загрузить PDF
Загрузить PDF
Циклический избыточный код (ЦИК) — алгоритм вычисления, предназначенный для проверки данных, в частности на жестких и оптических дисках (то есть DVD и CD). Этот алгоритм применяется при нарушении целостности данных на жестком или оптическом диске.
Шаги
-
1
Узнайте причину наличия ошибки. Ошибка на жестком диске возникает в случае некорректной записи данных. Причиной этого может служить нарушение работы операционной системы или потеря питания при записи данных.
-
2
Для того чтобы исправить циклическую ошибку жесткого диска, запустите приложение «Проверка диска». В папке «Мой компьютер» нажмите правым щелчком мыши на пострадавший жесткий диск и выберите «Свойства».
-
3
В большинстве случаев этот метод не сработает, потому что в Графическом интерфейсе пользователя не будут отображены все свойства диска. Интерфейс закроется без какой-либо проверки диска. Альтернативой этому способу является запуск команды из командной строки как показано ниже:
- 1. Запустите командную строку в качестве администратора.
- 2. Введите chkdsk G: /f /r («G» определяет поврежденный жесткий диск).
- 3. RЗапустите приложение DiskPart из этой же командной строки, введя DiskPart.
- 4. После запуска приложения, включите команду сканирования. Эта команда находит новые диски, которые были подключены к компьютеру.
- 5. Надейтесь, что проблема будет решена, и вы сможете просмотреть жесткий диск.
-
4
Вы можете просмотреть журнал уведомлений CHKDSK, нажав правой кнопкой мыши на «Мой компьютер» и выбрав пункт «Управление».
-
5
Нажмите правой кнопкой мыши на ‘Мой компьютер’ -> Управление -> Просмотр событий -> Уведомления.
-
6
Не нужно следовать дальнейшим указаниям.
-
7
#*Вы увидите уведомление, говорящее о том, что для выполнения проверки вам необходимо перезагрузить компьютер. Нажмите на кнопку «Расписание», а затем перезагрузите компьютер.
-
8
В свойствах диска зайдите на вкладку «Сервис» и нажмите «Выполнить проверку…». Появится небольшое окно, убедитесь, что рядом с опциями «Автоматически исправлять системные ошибки» и «Проверять и восстанавливать поврежденные сектора» поставлены флажки. Затем нажмите «Запуск».
-
9
Примечание: Если оптический диск (то есть DVD/BD/CD диски) сообщает о циклической ошибке, знайте, что не существует способа ее исправить. Если вы сами записывали информацию на диск, попробуйте записать ее же на другой диск, но теперь на более низкой скорости записи. Рекомендованной скоростью записи данных является 4х, особенно в тех случаях, когда вы записываете на диск операционную систему (Ubuntu, Windows). Чем выше скорость записи данных, тем выше вероятность записи ошибок на диск.
Реклама
Советы
- Диск может сообщать об ошибке, если на нем есть грязь или при наличии царапин. Если информация на диске вам очень важна, попробуйте протереть его и заделать царапины в том случае, если они небольшие.
Реклама
Предупреждения
- В случае с жестким диском, постоянные циклические ошибки могут быть предостережением скорой поломки диска. На всякий случай сделайте копию всей важной информации.
Реклама
Об этой статье
Эту страницу просматривали 14 228 раз.
Была ли эта статья полезной?
Summary: In this blog, we are going to discuss SQL Database Cyclic Redundancy Check (CRC) error. Also, we will discuss the possible reasons behind the error, and scenarios in which you can encounter the CRC error. Plus, we will look at a few solutions to fix SQL CRC error. You may also try Stellar Repair for MS SQL software to repair and restore your SQL database in a few simple steps, without having to spend several hundreds of man-hours and IT resources.
Contents
- What is CRC?
- Occurrences of SQL CRC Error
- How to Fix SQL CRC Error?
- Conclusion
SQL Server operations are highly dependent on the disk subsystem. It is without a doubt a key component to SQL Server performance and availability as storage. Sometimes, an issue with the I/O subsystem can lead to Cyclic Redundancy Check (CRC) error. The error message reads as:
Encountered error: Msg 823, Level 24, State 2, Line 1
I/O error 23(Data error (cyclic redundancy check).) detected during read at offset 0x000001ac1c4000 in file ‘C:Program FilesMicrosoft SQL ServerMSSQL13.SQL2K16MSSQLDATAMoreData.mdf’.
You may encounter CRC data error in SQL database when performing any of these actions:
- Backup and restoring of the database
- Querying the database
- Starting SQL Server
Before we jump into identifying the root cause for this error and find its solution, let us first understand what does cyclic redundancy check means.
What is CRC?
A Cyclic Redundancy Check (CRC) is a data verification algorithm that computers use to check the data on storage devices like SSD, HDD, CDs, Magnetic tapes, and more.
What Causes Cyclic Redundancy Check Error in SQL Database?
SQL cyclic redundancy check error may occur due to any of these reasons:
- Registry Corruption
- Cluttered hard disk
- Unsuccessful program installation
- Misconfigured files
- File written on bad sector of hard disk
Regardless of the specific cause, the cyclic redundancy check error is a serious error and must be addressed immediately to avoid potential data loss or even total system failure.
Occurrences of SQL CRC Error
Following are two scenarios in which you may encounter the CRC error:
Scenario 1: You may get the error when backing up a database. When you encounter the error during a backup, you can revisit the SQL Server error logs to get more details on the error.
Example of verbose log is shown below:
10/18/2016 12:00:19 AM Creating backup of MoreData to C:Program FilesMicrosoft SQL ServerMSSQL13.SQL2K16MSSQLBackup
10/18/2016 12:00:32 AM ERROR: Read on “C:Program FilesMicrosoft SQL ServerMSSQL13.SQL2K16MSSQLDATAMoreData.MDF” failed: 23(Data error (cyclic redundancy check).)
BACKUP DATABASE is terminating abnormally.
10/18/2016 12:00:32 AM ERROR: Job finished (With Errors)
Scenario 2: The next scenario is when you are querying the SQL database and it stops abruptly with the data check error. When querying the database, you will receive CRC error on SQL Server Management Studio (SSMS) error pane. The error message reads as:
Server: Msg 823, Level 24, State 2, Line 1
I/O error 23(Data error (cyclic redundancy check).) detected during read at offset 0x000001ac1c4000 in file ‘C:Program FilesMicrosoft SQL ServerMSSQL13.SQL2K16MSSQLDATAMoreData.mdf’.
How to Fix SQL CRC Error?
Follow the steps in the sequence given below to resolve the error:
Step 1: Since the root cause behind the CRC error is an I/O subsystem issue, it is important to fix the underlying storage issues. That, in turn, would most likely fix the cyclic redundancy check error in SQL.
Run the CHKDSK utility on the disk in question and allow it to fix any error by using the /F parameter. Below is a screenshot of the command to check and fix the F: drive:
Step 2: A complete disk defragmentation is recommended after the “chkdsk” is completed with a successful repair of any errors.
Step 3: Perform a data integrity check on the SQL database to make sure that data is not corrupt. Run the command as highlighted below and analyze the results:
DBCC CHECKDB (MoreData) WITH NO_INFOMSGS, ALL_ERRORMSGS
Running the above command, detected 2 allocation errors and 1 consistency error as shown below:
Server: Msg 8946, Level 16, State 12, Line 2
Table error: Allocation page (1:72864) has invalid PFS_PAGE page header values. Type is 0. Check type, object ID and page ID on the page.
Server: Msg 8921, Level 16, State 1, Line 1
CHECKTABLE terminated. A failure was detected while collecting facts. Possibly tempdb out of space or a system table is inconsistent. Check previous errors.
Server: Msg 8966, Level 16, State 1, Line 1
Could not read and latch page (1:72864) with latch type UP. failed.
Server: Msg 8966, Level 16, State 1, Line 1
Could not read and latch page (1:72864) with latch type UP. failed.
Server: Msg 8998, Level 16, State 1, Line 1
Page errors on the GAM, SGAM, or PFS pages do not allow CHECKALLOC to verify database ID 8 pages from (1:72864) to (1:80879). See other errors for cause.
CHECKDB found 2 allocation errors and 1 consistency errors not associated with any single object.
CHECKDB found 2 allocation errors and 1 consistency errors in database ‘MoreData’
Step 4: At this point, we are facing database corruption, and our options are to either restore the most recent backup or repair the database either by using SQL native repair commands or third-party tools. Now let’s look at both these options:
Restore database from Clean Backup
When trying to restore the db from backup, it is highly recommended to perform a RESTORE VERIFYONLY on the backup file to know if the backup is in a consistent state.
RESTORE VERIFYONLY FROM DISK = C:BackupFileMoreData.BAK GO
Repair the Corrupt SQL database
If the restore does not come out clean, then we are running out of options and would need to start looking into repairing the database. We can attempt to repair SQL database by using the DBCC CHECKDB with REPAIR OPTION.
For detailed information on DBCC CHECKDB, read this: How to Repair SQL Database using DBCC CHECKDB Command
Try repairing the db with DBCC CHECKDB ‘Repair_Allow_Data_Loss’ option by running the following code:
USE master; ALTER DATABASE [CorruptDB] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO DBCC CHECKDB ('CorruptDB', REPAIR_ALLOW_DATA_LOSS) WITH NO_INFOMSGS; GO ALTER DATABASE [CorruptDB] SET MULTI_USER; GO
What If DBCC CHECKDB Fails to Repair SQL Database?
Repairing the database using the DBCC CHECKDB with ‘Repair_Allow_Data_Loss’ involves data loss risk during the repair process. It may also not deliver expected results. Use Stellar Database repair tool to fix a corrupt SQL database. The tool serves as the best Alternative of DBCC CHECKDB Repair Allow Data Loss that helps repair a SQL database from all types of common SQL database corruption errors. It repairs corrupt MDF and NDF files and restores all the database objects. Also, it helps restore the database back to its original state without any risk of data loss.
Essentially, the software helps repair corrupt SQL Server database (.mdf and .ndf) files, while maintaining the original structure and integrity of database objects.
Conclusion
So, there you have it! If you have a good disaster recovery plan set up, then you should have no problems when your production database or any other database gets corrupted due to SQL Database Cyclic Redundancy Check (CRC) error. Now let’s say you find yourself in a situation where a proper DR plan was not established and you do not have any backups to restore. You can consider utilizing the minimal repair level reported by the DBCC CHECKDB when you run the integrity check on the suspect database.
Remember that the repair feature of SQL Server is not robust and not a guaranteed solution. For a faster, more versatile repair that would bring your SQL corrupt database back into a working start with minimal data loss, look no further than Stellar Repair for MS SQL software. It repairs the database faster by using a more sophisticated repair algorithm. It can even recover deleted data in your database.
About The Author
Samuel Okudjeto
Samuel Okudjeto is a technology enthusiast with great interest in database administration and analytics. He has many certifications including the Microsoft Certified Expert Professional. Along with 6+ years of hands-on experience, he holds a Masters of Science degree in Business Analytics. Read more
Best Selling Products
Stellar Repair for MS SQL
Stellar Repair for MS SQL is an enterpri
Read More
Stellar Toolkit for MS SQL
3-in-1 software package, recommended by
Read More
Stellar Converter for Database
Stellar Converter for Database is an eff
Read More
Stellar Repair for Access
Powerful tool, widely trusted by users &
Read More
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:Выберите жесткий диск
- Шаг 2:Сканировать жесткий диск
- Шаг 3:Предварительный просмотр и восстановление файлов
Подключите внешний накопитель и найдите его на 4DDiG. Затем нажмите кнопку сканировать, чтобы продолжить. В следующих всплывающих окнах вы можете настроить типы файлов, чтобы начать сканирование.
4DDiG немедленно проверяет выбранный диск на предмет отсутствия данных, и вы можете приостановить или прекратить поиск в любое время, если определили файлы, которые хотите восстановить. В древовидном представлении есть такие категории, как Удаленные файлы, Существующие файлы, Потерянное местоположение, Необработанные файлы и Файлы тегов. Вы также можете переключиться в режим просмотра файлов, чтобы проверить такие типы файлов, как Фото, видео, Документ, Аудио, электронная почта и другие. Кроме того, вы можете искать целевые файлы или использовать фильтр, чтобы сузить область поиска в левой части панели.
После обнаружения целевых файлов вы можете просмотреть их и восстановить в безопасном месте. В случае перезаписи диска и необратимой потери данных, пожалуйста, не сохраняйте их в том же разделе, где вы их потеряли.
После восстановления данных теперь вы можете приступить к исправлению этой ошибки.
Исправление 1: Запустите проверку диска для устранения неполадок
Самое замечательное в Windows то, что в ней есть множество инструментов, которые вы можете использовать для устранения ошибки циклической проверки избыточности данных ошибка жесткого диска. Проверка диска — один из них и один из самых безопасных для сохранения ваших данных во время исправления. Вот как вы можете его использовать.
Шаг 1: Перейдите в раздел «Мой компьютер», щелкните правой кнопкой мыши раздел с ошибкой и перейдите в раздел «Свойства».
Шаг 2: Оказавшись в окне свойств, перейдите на вкладку Инструменты и нажмите опцию «Проверить сейчас» в разделе проверка ошибок.
Шаг 3: Теперь вы можете выбрать сканирование диска для устранения неполадок и устранения ошибки CRC.
Исправление 2: Используйте утилиту CHKDSK для восстановления жесткого диска
CHKDSK — это утилита для решения большинства проблем, связанных с данными в Windows, и diskpart столкнулся с ошибкой ошибка данных (циклическая проверка избыточности) ничем не отличается. Чтобы использовать CHKDSK для решения этой проблемы, выполните следующие действия:
Step 1: Откройте командную строку и выберите запуск от имени администратора. Введите следующую команду: chkdsk /r x:‘. Здесь x — это конкретный диск, который выдает вам ошибку.
Step 2: Утилита CHKDSK теперь просканирует раздел, выдаст вам отчет и перезагрузит ваш компьютер. Ваше устройство будет исправлено при запуске, если этот метод сработает. Если нет, переходите к следующему.
Исправление 3: Запустите SFC-сканирование для восстановления системных файлов
Если источником этой ошибки является логическая проблема с вашим жестким диском, то проверка системных файлов (SFC) также может решить вашу проблему. Вот как это делается:
Step 1: Запустите командную строку от имени администратора и введите следующую команду «sfc /scannow«.
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 (англ. Cycle Redundancy Check) является алгоритмом вычисления контрольной суммы файла, используемой для проверки корректности передаваемой информации. То есть в результате обработки информации получается определённое значение, которое обязательно будет разным для файлов, даже на один бит отличающихся между собой. Так, алгоритм, базирующийся на циклическом коде, определяет контрольную сумму и приписывает её к передаваемым данным. В свою очередь принимающая сторона также владеет алгоритмом нахождения контрольной суммы, что даёт возможность системе проверить целостность получаемых данных. Когда эти числа соответствуют, информация передаётся успешно, а при несовпадении значений контрольной суммы возникает ошибка в данных CRC, это означает, что файл, к которому обратилась программа, был изменён или повреждён.
Причины возникновения ошибки CRC
В большинстве случаев проблема носит аппаратный характер, но иногда возникает и по программным причинам. Сообщение «Ошибка данных в CRC» может говорить о неисправности HDD, нарушении файловой системы или наличии битых секторов. Нередко сбой возникает при инициализации жёсткого диска или твердотельного накопителя SSD после подсоединения к компьютеру, несмотря на конструктивные отличия и разницу в способе функционирования, это происходит, поскольку не удаётся правильно прочитать данные. Тогда неполадка может заключаться не только в механических повреждениях, но и в неисправности интерфейсов подключения или плохом контакте. Ошибка в устройствах SSD с интерфейсом PCI-E также случается из-за накопившихся загрязнений на плате. Проблемы с доступом к внешним накопителям нередко связаны с неисправностью портов. Среди программных причин ошибку в данных CRC способны вызывать сбои драйверов устройств. Источником проблемы при установке программного обеспечения посредством торрент-клиента чаще всего является повреждённый архив. Таким образом, можно выделить следующие причины ошибки CRC:
- Случайный сбой во время установки софта.
- Потеря или повреждение данных при их передаче.
- Загрузка повреждённого архива.
- Неправильные записи системного реестра.
- Некорректные драйверы устройств.
- Повреждение оптического диска.
- Неисправность разъёмов.
- Повреждение секторов жёсткого диска, файловой системы HDD.
- Неправильная конфигурация файлов и другие причины.
Как исправить ошибку 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, которая считывает и возвращает к жизни файлы с испорченных накопителей, если это возможно. К сожалению, при сильно выраженных повреждениях диска скопировать с него файлы не удастся.
Ошибка в данных CRC при записи оптического диска, установке программ или игр
Если проблема возникла в процессе записи образа, скачанного с просторов интернета, на CD/DVD, стоит проверить контрольные суммы записываемых данных перед выполнением процедуры. Для этой цели используется утилита HashTab, после установки которой, в свойствах файла появится новая вкладка «Хеш-суммы файлов», с её помощью вы сможете сравнить значение с исходником. Так, при несовпадении контрольных сумм, следует скачать образ снова.
Повторно скачать файл или архив следует также, когда с помощью скачанного дистрибутива программы она не устанавливается на компьютер. Данные могли быть повреждены в процессе загрузки или не были полностью выкачаны. Удобно применять для скачивания uTorrent, поскольку утилита самостоятельно определяет значения контрольных сумм и перекачивает часть информации, загрузившейся с ошибкой. В случае скачивания данных по прямым ссылкам можно использовать Download Master. При этом не исключено, что архив или файл уже был повреждён изначально и в таком виде залит на ресурс, потому нужно попробовать скачать его с альтернативного источника.
Ошибка в uTorrent
Когда ошибка в данных CRC появляется в программе uTorrent, исправляем её следующими действиями:
- Выполняем обновление клиента.
- Удаляем проблемную раздачу в программе, а также недокачавшийся файл в папке на компьютере.
- Ищем аналогичную раздачу на другом ресурсе и скачиваем оттуда.
Вышеперечисленных способов достаточно, чтобы избавиться от ошибки в данных CRC, возникающей при различных условиях. Так, определив источник появления сбоя, можно целенаправленно устранить проблему. В большинстве случаев исправить ошибку удаётся программными средствами, но, когда речь идёт о физической неисправности накопителя, следует задуматься о его замене.