How to Write a CRC-CCITT 16-Bit Error Detection Program in C
A CRC-CCITT error-detection program uses a 16-bit register, the 0x1021 polynomial, and a transmitted 16-bit check value to detect accidental changes in data. This version uses an initial register value of 0xFFFF, processes bytes most-significant bit first without reflection, appends two zero bytes during calculation, and produces 0xE5CC for the test string "123456789".
A CRC does not repair corrupted data or identify the changed byte. It lets the receiver determine whether the bytes it received still match the bytes the sender protected.
How CRC-CCITT Detects Transmission Errors
CRC stands for cyclic redundancy check. The sender calculates a small check value from a message, appends that value to the message, and sends both. The receiver runs the same calculation on the received message and compares its result with the appended value.
For CRC-CCITT, the division rule comes from this polynomial:
x^16 + x^12 + x^5 + 1
In C code, the leading x^16 term is implicit, so the polynomial is written as 0x1021. Do not substitute 0x8005: that is a different CRC polynomial and creates incompatible results.
A CRC works only when the sender and receiver use exactly the same parameters and cover exactly the same bytes.
This article implements an augmented CRC-CCITT calculation. It processes the message and then processes two NULL bytes, 16 zero bits, as part of the calculation. Those zero bytes are conceptual calculation input; you do not add them to the transmitted payload.
How to Write the CRC-CCITT Program in C
Use this parameter set when both ends of your protocol need the augmented CRC-CCITT calculation shown here.
| Parameter | Value for This Program | Why It Matters |
|---|---|---|
| CRC width | 16 bits | The result fits in uint16_t. |
| Polynomial | 0x1021 |
Represents x^16 + x^12 + x^5 + 1. |
| Initial register | 0xFFFF |
Used before processing the first input byte. |
| Bit order | MSB first, unreflected | Each byte enters at the high end of the register. |
| Augmentation | Two zero bytes | Represents 16 appended zero bits after the message. |
| Final XOR | None | The final register value is the transmitted CRC. |
| Wire byte order | High byte, then low byte | Sender and receiver must agree on CRC byte order. |
Step 1: Define the CRC Update Function
The update function accepts one data byte and shifts it through the CRC register one bit at a time. It tests the register’s top bit before each shift. When that bit is set, the code XORs the shifted value with 0x1021.
static uint16_t crc16_ccitt_update(uint16_t crc, uint8_t byte)
{
crc = (uint16_t)(crc ^ ((uint16_t)byte << 8));
for (unsigned int bit = 0; bit < 8; ++bit) {
if ((crc & 0x8000u) != 0u) {
crc = (uint16_t)((crc << 1) ^ 0x1021u);
} else {
crc = (uint16_t)(crc << 1);
}
}
return crc;
}
This is a bitwise implementation rather than a lookup-table implementation. It is easy to audit, uses very little memory, and is usually appropriate for small messages and embedded projects.
Step 2: Calculate the Augmented CRC
Start the register at 0xFFFF, process each payload byte, then process two zero bytes. Processing those final zero bytes performs the required 16-bit augmentation.
static uint16_t crc16_ccitt(const uint8_t *data, size_t length)
{
uint16_t crc = 0xFFFFu;
for (size_t index = 0; index < length; ++index) {
crc = crc16_ccitt_update(crc, data[index]);
}
/* Append 16 zero bits to the calculation, not to the wire payload. */
crc = crc16_ccitt_update(crc, 0x00u);
crc = crc16_ccitt_update(crc, 0x00u);
return crc;
}
Do not reflect the bytes, reverse the final CRC bits, or apply a final XOR in this implementation. Any of those changes creates a different CRC variant.
Step 3: Add Frame Verification Code
A receiver needs to split the received frame into two parts:
- The protected payload.
- The final two CRC bytes.
The frame verification function assumes the sender places the CRC high byte first and low byte second.
static bool frame_is_valid(const uint8_t *frame, size_t frame_length)
{
enum { CRC_BYTES = 2 };
if (frame == NULL || frame_length < CRC_BYTES) {
return false;
}
size_t payload_length = frame_length - CRC_BYTES;
uint16_t received_crc =
(uint16_t)(((uint16_t)frame[payload_length] << 8) |
frame[payload_length + 1]);
uint16_t calculated_crc = crc16_ccitt(frame, payload_length);
return calculated_crc == received_crc;
}
A valid CRC means the frame passed an integrity check. The frame is not safe to trust against an attacker, because an attacker can alter both the payload and its CRC. Use authentication such as a MAC, authenticated encryption, or a digital signature when malicious modification is a concern.
Step 4: Build a Complete Test Program
Save the following program as crc_ccitt.c. It calculates the known test value, builds a frame, verifies the unchanged frame, then flips one bit to demonstrate detection of corruption.
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CRC16_CCITT_POLY 0x1021u
static uint16_t crc16_ccitt_update(uint16_t crc, uint8_t byte)
{
crc = (uint16_t)(crc ^ ((uint16_t)byte << 8));
for (unsigned int bit = 0; bit < 8; ++bit) {
if ((crc & 0x8000u) != 0u) {
crc = (uint16_t)((crc << 1) ^ CRC16_CCITT_POLY);
} else {
crc = (uint16_t)(crc << 1);
}
}
return crc;
}
static uint16_t crc16_ccitt(const uint8_t *data, size_t length)
{
uint16_t crc = 0xFFFFu;
for (size_t index = 0; index < length; ++index) {
crc = crc16_ccitt_update(crc, data[index]);
}
/* Augment the calculation with two zero bytes. */
crc = crc16_ccitt_update(crc, 0x00u);
crc = crc16_ccitt_update(crc, 0x00u);
return crc;
}
static bool frame_is_valid(const uint8_t *frame, size_t frame_length)
{
enum { CRC_BYTES = 2 };
if (frame == NULL || frame_length < CRC_BYTES) {
return false;
}
size_t payload_length = frame_length - CRC_BYTES;
uint16_t received_crc =
(uint16_t)(((uint16_t)frame[payload_length] << 8) |
frame[payload_length + 1]);
return crc16_ccitt(frame, payload_length) == received_crc;
}
int main(void)
{
enum { CRC_BYTES = 2 };
static const uint8_t test_data[] = "123456789";
const size_t payload_length = sizeof(test_data) - 1;
uint16_t crc = crc16_ccitt(test_data, payload_length);
printf("CRC for 123456789: %04X\n", crc);
if (crc != 0xE5CCu) {
fprintf(stderr, "Known-answer test failed.\n");
return EXIT_FAILURE;
}
uint8_t frame[sizeof(test_data) - 1 + CRC_BYTES];
memcpy(frame, test_data, payload_length);
/* Put the 16-bit CRC on the wire in high-byte-first order. */
frame[payload_length] = (uint8_t)(crc >> 8);
frame[payload_length + 1] = (uint8_t)(crc & 0xFFu);
printf("Unchanged frame: %s\n",
frame_is_valid(frame, sizeof(frame)) ? "valid" : "invalid");
/* Simulate corruption of one payload bit. */
frame[3] ^= 0x01u;
printf("Changed frame: %s\n",
frame_is_valid(frame, sizeof(frame)) ? "valid" : "invalid");
return EXIT_SUCCESS;
}
Step 5: Compile and Run the Program
Compile the C99 source with a standard C compiler:
cc -std=c99 -Wall -Wextra -O2 crc_ccitt.c -o crc_ccitt
Run the resulting executable:
./crc_ccitt
The output should show this CRC and two verification results:
CRC for 123456789: E5CC
Unchanged frame: valid
Changed frame: invalid
The known-answer test is important. If the first line is not E5CC, do not use the implementation in a protocol yet.
How to Add the CRC to a Protocol Frame
In a real application, decide which bytes belong to the protected message before writing code. A typical frame might contain a type byte, a length field, payload bytes, and then the CRC.
If you want the type and length to be protected, include them in the byte sequence passed to crc16_ccitt(). Do not calculate the CRC over only the payload on one side and over header-plus-payload on the other.
A sender follows this sequence:
- Build the exact header and payload bytes to protect.
- Calculate
crc16_ccitt(protected_bytes, protected_length). - Append the CRC high byte.
- Append the CRC low byte.
- Send the complete frame.
A receiver follows this sequence:
- Read enough bytes to establish the frame boundary safely.
- Reject frames shorter than two CRC bytes.
- Treat the final two bytes as the received CRC.
- Calculate the expected CRC across every protected byte before those final two bytes.
- Reject or request retransmission when the values differ.
- Parse the application payload only after the CRC passes.
Keep framing and CRC responsibilities separate. A CRC tells you whether a chosen byte sequence changed; it does not tell you where a message starts, where it ends, or whether a length field is plausible. Validate frame lengths and buffer bounds before accessing received data.
CRC-CCITT Variants and Compatibility
The name “CRC-CCITT” is not a complete wire-format specification. Different projects use that label for calculations with different initial values, reflection rules, final XOR values, and augmentation behavior.
A common source of confusion is the string "123456789":
- This augmented implementation returns
0xE5CC. - Some non-augmented implementations return
0x29B1. - Other CRC variants can use the same
0x1021polynomial but still return another value.
Neither result is automatically wrong in isolation. They are incompatible with each other.
Before connecting to an existing device, file format, bootloader, or serial protocol, obtain its complete CRC contract:
- polynomial;
- register width;
- initial value;
- input reflection;
- output reflection;
- final XOR;
- whether zero-bit augmentation is used;
- exact bytes covered;
- byte order of the transmitted CRC.
If the remote specification provides a sample message and expected CRC, turn it into an automated test before sending live data. That test is more reliable than matching a CRC name in a library menu.
Test and Troubleshoot the Implementation
Start with the known-answer test, then test the same messages your protocol will carry. Use byte arrays rather than C strings for binary data, because C strings stop at a 0x00 byte while a CRC must process every byte, including zero-valued bytes.
Test these cases:
- an empty payload;
- a one-byte payload;
- a payload containing
0x00; - bytes with the high bit set, such as
0x80or0xFF; - the largest frame your receiver accepts;
- a frame with one changed payload bit;
- a frame with one changed CRC bit;
- a truncated frame.
Common failures usually have a simple cause:
- The test value is
0x29B1instead of0xE5CC. The code likely omitted the two zero bytes used for augmentation. - Sender and receiver disagree on every frame. Check CRC byte order. One side may send low byte first while the other reconstructs high byte first.
- Only some messages fail. Verify whether headers, length bytes, delimiters, or escaping bytes are included consistently.
- Binary messages fail but text messages work. Look for
strlen()use, text conversion, signedcharhandling, or code that stops at a zero byte. - A lookup-table version disagrees with this code. Confirm the table was generated for unreflected
0x1021processing and uses the same initial value, augmentation, and final XOR behavior.
For debugging, log the protected byte count, the sender CRC, the receiver’s calculated CRC, and a hexadecimal dump of the exact protected bytes. Those four values usually expose a framing or parameter mismatch quickly.
Next, replace the demonstration string with your protocol’s actual byte sequence and add its expected CRC to your test suite. For embedded applications that periodically compare a calculated CRC with a stored reference value, Microchip’s CRC application note shows the same general reference-check pattern for detecting corrupted memory.
Frequently Asked Questions
How Do I Calculate CRC-16-CCITT in C?
Use a uint16_t register initialized to 0xFFFF, XOR each input byte into the register’s high byte, shift left through eight bits, and XOR with 0x1021 when the previous top bit was set. For the augmented form in this article, process two additional zero bytes after the message and do not apply a final XOR.
Why Does My CRC-CCITT Code Return 0x29B1 for 123456789?
Your implementation is probably using a non-augmented calculation that stops after processing the nine message bytes. The augmented CRC-CCITT method here processes two additional zero bytes after "123456789", producing 0xE5CC instead.
Does CRC-CCITT Correct Errors?
No. CRC-CCITT detects many accidental transmission, storage, and memory errors, but it does not identify the corrupted byte or reconstruct the original data. When verification fails, discard the frame, request retransmission, reload known-good data, or follow the failure policy for your system.
Should I Transmit the Two Added Zero Bytes?
No. The two zero bytes are part of the CRC calculation only; they are not payload bytes and are not appended to the transmitted frame. Send the original protected bytes followed by the two-byte CRC value.
Can I Use CRC-CCITT for Security?
No. CRC-CCITT is an integrity check for accidental corruption, not a security mechanism. An attacker can calculate a replacement CRC after changing a message, so use a cryptographic MAC or authenticated encryption for untrusted data.
