# comm.CRCGenerator

Generate CRC code bits and append to input data

## Description

The `comm.CRCGenerator`

System object™ generates cyclic redundancy check (CRC) code bits for each input frame and
appends them to the frame. For more information, see CRC Generator Operation.

To generate CRC code bits for each input frame and append them to the frame:

Create the

`comm.CRCGenerator`

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
CRC code generator System object. This object generates CRC bits according to a specified generator
polynomial and appends them to the input frame.`crcgenerator`

= comm.CRCGenerator

sets properties using one or more name-value pairs. For example,
`crcgenerator`

= comm.CRCGenerator(`Name`

,`Value`

)`comm.CRCGenerator('Polynomial','z^16 + z^14 + z + 1')`

configures the
CRC generator System object to append CRC-16 cyclic redundancy check bits to the input frame. Enclose
each property name in quotes.

creates a CRC code generator System object. This object has the `crcgenerator`

= comm.CRCGenerator(poly,`Name`

,`Value`

)`Polynomial`

property
set to `poly`

, and the other specified properties set to the specified
values.

## Properties

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*z*^{3}+*z*^{2}+ 1.An integer row vector containing the exponents of

*z*for the nonzero terms in the polynomial in descending order. For example,`[3 2 0]`

represents the polynomial*z*^{3 }+*z*^{2 }+ 1.

For more information, see Representation of Polynomials in Communications Toolbox.

The default value is the CRC-16-CCITT generator polynomial. This table lists some commonly used generator polynomials.

CRC Name | 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'` |

CRC-16-CCITT | `'z^16 + z^12 + z^5 + 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
input frame on a bytewise basis before entering the data into the shift register.

When you set this property to `true`

, the input frame 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 input data are completely through the shift
register.

**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 for each frame

1 (default) | positive integer

Number of checksums calculated for each frame, specified as a positive integer. For more information, see CRC Generator Operation.

**Data Types: **`double`

## Usage

### Description

### Input Arguments

`X`

— Input signal

binary column vector

Input signal, specified as a binary column vector. The length of the input frame
must be a multiple of the value of the `ChecksumsPerFrame`

property. If the input data type is double, the least significant bit is used as the
binary value. For more information, see CRC Generator Operation.

This object accepts variable-size inputs. After the object is locked, you can change the size of each input channel, but you cannot change the number of channels. For more information, see Variable-Size Signal Support with System Objects.

**Data Types: **`double`

| `logical`

### Output Arguments

`codeword`

— Output codeword frame

binary column vector

Output codeword frame, returned as a binary column vector that inherits the data type of the input signal. The output contains the input frames with the CRC code sequence bits appended.

The length of the output codeword frame is *m* +
*k* * *r*, where *m* is the size
of the input message, *k* is the number of checksums per input frame,
and *r* is the degree of the generator polynomial. For more
information, see CRC Generator Operation.

## 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:

release(obj)

## Examples

### 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.

x = randi([0 1],12,1);

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)
```

`err = `*2×1*
0
0

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)

`err = `*2×1*
0
1

### CRC-32 Generator for Ethernet

Create a CRC-32 code for the frame check sequence (FCS) field for Ethernet as described in Section 3.2.9 of the IEEE Standard for Ethernet[1].

`rng(1865); % Seed for repeatable results`

Initialize a message with random data to represent the protected fields of the MAC frame, specifically the destination address, source address, length or type field, MAC client data, and padding.

data = randi([0,1],100,1);

Specify the CRC-32 generating polynomial used for encoding Ethernet messages.

poly = [32,26,23,22,16,12,11,10,8,7,5,4,2,1,0];

Calculate the CRC by following the steps specified in the standard and using the nondirect method to generate the CRC code.

% Section 3.2.9 step a) and b) dataN = [not(data(1:32));data(33:end)]; crcGen1 = comm.CRCGenerator(... 'Polynomial',poly, ... 'InitialConditions',0, ... 'DirectMethod',false, ... 'FinalXOR',1); % Section 3.2.9 step c), d) and e) seq = crcGen1(dataN); csNondirect = seq(end-31:end);

Calculate the CRC by following the steps specified in the standard and using the direct method to generate the CRC code.

crcGen2 = comm.CRCGenerator( ... 'Polynomial',poly, ... 'InitialConditions',1, ... 'DirectMethod',true, ... 'FinalXOR',1); txSeq = crcGen2(data); csDirect = txSeq(end-31:end);

Compare the generated CRC codes by using the nondirect and direct methods.

disp([csNondirect';csDirect']);

1 1 1 0 1 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 1 1 0 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 0 0 1 0 0 1 0 1 0 0 1 0 1 0 1 1 0 0 0 1 1 1 0 0 1 0

isequal(csNondirect,csDirect)

`ans = `*logical*
1

rng('default'); % Reset the random number generator

**References**

[1] IEEE Computer Society. *IEEE Standard for Ethernet: Std 802.3-2012.* New York, NY: 2012.

## Algorithms

### Cyclic Redundancy Check Coding

Cyclic redundancy check (CRC) coding is an error-control coding technique for detecting errors that occur when transmitting a data frame. Unlike block or convolutional codes, CRC codes do not have a built-in error-correction capability. Instead, when a communications system detects a CRC coding 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 features that support matrix inputs, each column of input data is processed independently.

### Direct and Indirect CRC Algorithm

The `comm.CRCGenerator`

System object supports generation and detection of CRC checksum by using the indirect or
direct CRC algorithm.

**Indirect CRC Algorithm**

The indirect CRC algorithm accepts a binary data vector, corresponding to a polynomial *M*, and appends a checksum of *r* bits, corresponding to a polynomial *C*. The concatenation of the input vector and the checksum then corresponds to the polynomial *T* = *M*×*x*^{r} + *C*, since multiplying by *x*^{r} corresponds to shifting the input vector *r* bits to the left. The algorithm chooses the checksum *C* so that *T* is divisible by a predefined polynomial *P* of degree *r*, called the *generator polynomial*.

The algorithm divides *T* by *P*, and sets the checksum equal to the binary vector corresponding to the remainder. That is, if *T* = *Q*×*P* + *R*, where *R* is a polynomial of degree less than *r*, the checksum is the binary vector corresponding to *R*. If necessary, the algorithm prepends zeros to the checksum so that it has length *r*.

The CRC generation feature, which implements the transmission phase of the CRC algorithm, does the following:

Left shifts the input data vector by

*r*bits and divides the corresponding polynomial by*P*.Sets the checksum equal to the binary vector of length

*r*, corresponding to the remainder from step 1.Appends the checksum to the input data vector. The result is the output vector.

The CRC detection feature computes the checksum for its entire input vector, as described above.

The CRC algorithm uses binary vectors to represent binary polynomials, in descending order of powers. For example, the vector `[1 1 0 1]`

represents the polynomial *x*^{3 }+ *x*^{2 }+ 1.

Bits enter the linear feedback shift register (LFSR) from the lowest index bit to the highest index bit. The sequence of input message bits represents the coefficients of a message polynomial in order of decreasing powers. The message vector is augmented with *r* zeros to flush out the LFSR, where *r* is the degree of the generator polynomial. If the output from the leftmost register stage d(1) is a 1, then the bits in the shift register are XORed with the coefficients of the generator polynomial. When the augmented message sequence is completely sent through the LFSR, the register contains the checksum [d(1) d(2) . . . d(r)]. This is an implementation of binary long division, in which the message sequence is the divisor (numerator) and the polynomial is the dividend (denominator). The CRC checksum is the remainder of the division operation.

**Direct CRC Algorithm**

This block diagram shows the direct CRC algorithm.

Where **Message Block Input** is $${m}_{0},\text{\hspace{0.17em}}{m}_{1},\text{\hspace{0.17em}}\mathrm{...}\text{\hspace{0.17em}},\text{\hspace{0.17em}}{m}_{k-1}$$ and **Code Word Output** is

$${c}_{0},\text{\hspace{0.17em}}{c}_{1},\mathrm{...}\text{}\text{}\text{\hspace{0.17em}},\text{}\text{\hspace{0.17em}}{c}_{n-1}=\underset{X}{\underbrace{{m}_{0},\text{\hspace{0.17em}}{m}_{1},\mathrm{...}\text{}\text{}\text{\hspace{0.17em}},{m}_{k-1},}}\underset{Y}{\underbrace{{d}_{0},{d}_{1},\text{\hspace{0.17em}}\mathrm{...}\text{\hspace{0.17em}},\text{\hspace{0.17em}}{d}_{n-k-1}}}$$

The initial step of the direct CRC encoding occurs with the three switches in position *X*. The algorithm feeds *k* message bits to the encoder. These bits are the first *k* bits of the code word output. Simultaneously, the algorithm sends *k* bits to the linear feedback shift register (LFSR). When the system completely feeds the *k*th message bit to the LFSR, the switches move to position *Y*. Here, the LFSR contains the mathematical remainder from the polynomial division. These bits are shifted out of the LFSR and they are the remaining bits (checksum) of the code word output.

### CRC Generator Operation

The CRC generator appends CRC checksums to the input frame according to the specified generator polynomial and number of checksums per frame.

For a specific initial state of the internal shift register and *k* checksums
per input frame:

The input signal is divided into

*k*subframes of equal size.Each of the

*k*subframes are prefixed with the initial states vector.The CRC algorithm is applied to each subframe.

The resulting checksums are appended to the end of each subframe.

The subframes are concatenated and output as a column vector.

For the scenario shown here, a 10-bit frame is input, a *z*^{3} +
*z*^{2} + 1 generator polynomial computes the CRC checksum, the initial state is 0,
and the number of checksums per frame is 2.

The input frame is divided into two subframes of size 5, and checksums of size 3 are computed
and appended to each subframe. The initial states are not shown because an initial state of
`[0]`

does not affect the output of the CRC algorithm. The output
transmitted codeword frame has the size 5 + 3 + 5 + 3 = 16 bits.

## 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

### C/C++ Code Generation

Generate C and C++ code using MATLAB® Coder™.

Usage notes and limitations:

See System Objects in MATLAB Code Generation (MATLAB Coder).

## See Also

### Functions

### Objects

### Blocks

## MATLAB Command

You clicked a link that corresponds to this MATLAB command:

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

## How to Get Best Site Performance

Select the China site (in Chinese or English) for best site performance. Other MathWorks country sites are not optimized for visits from your location.

### Americas

- América Latina (Español)
- Canada (English)
- United States (English)

### Europe

- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)

- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)