Simvik

CRC-16 for Modbus

Implement the reflected CRC-16 used by Modbus RTU. A medium embedded C problem (Protocols, framing and checksums), run and graded in the browser.

medium · Protocols, framing and checksums · crc · modbus

Modbus RTU uses a CRC-16 that processes the least significant bit first: initial value 0xFFFF, reflected polynomial 0xA001, no final XOR.

For each byte: XOR it into the low byte of the CRC, then repeat eight times: if the lowest bit is set, shift right and XOR with 0xA001; otherwise just shift right.

Starter code

uint16_t crc16_modbus(const uint8_t *data, size_t n) {
  uint16_t crc = 0xFFFF;
  // For each byte: crc ^= byte, then 8 right-shift steps with a conditional XOR of 0xA001.
  return crc;
}

Example tests

Standard check value

printf("0x%04X\n", crc16_modbus((const uint8_t *)"123456789", 9));

Expected output:

0x4B37

A read-holding-registers request

const uint8_t req[] = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x0A };
printf("0x%04X\n", crc16_modbus(req, sizeof req));

Expected output:

0xCDC5

Learn it first

More Protocols, framing and checksums problems