CRC-16 Checksum Calculator

CRC-16 cyclic redundancy check calculator supporting multiple CRC-16 algorithms

Need CRC-8 or CRC-32? Open the general CRC calculator

Tool Overview: CRC-16 Checksum Calculator

CRC-16 (16-bit Cyclic Redundancy Check) is a widely used error detection algorithm primarily used for integrity verification in data transmission and storage. This tool supports multiple CRC-16 algorithm variants suitable for different application scenarios.

What Is CRC-16 Checksum Calculator?

CRC-16 Checksum Calculator encodes/decodes content or generates checksums for verification.

How to Use

  1. Paste the content or input text.
  2. Choose the encoding or hashing mode.
  3. Copy the generated result.

Common Use Cases

  • Signatures and integrity checks
  • Safe transfer between systems
  • Quick verification during debugging

❓ FAQ

Q1: Different results for same input?
A: Check encoding and hidden characters.

Q2: Can I reverse it?
A: Encoding is reversible; hashes are not.

Q3: Large input?
A: Split into smaller parts for stability.

🔧 Supported Algorithms

CRC-16 Standard

  • Polynomial: 0x8005 (x^16 + x^15 + x^2 + 1)
  • Initial Value: 0x0000
  • Application: General data verification

CRC-16 CCITT

  • Polynomial: 0x1021 (x^16 + x^12 + x^5 + 1)
  • Initial Value: 0xFFFF
  • Application: Communication protocols, X.25, HDLC

CRC-16 Modbus

  • Polynomial: 0x8005
  • Initial Value: 0xFFFF
  • Application: Modbus communication protocol

CRC-16 XMODEM

  • Polynomial: 0x1021
  • Initial Value: 0x0000
  • Application: XMODEM file transfer protocol

💡 Use Cases

1. Data Integrity Verification

// Data transmission integrity check
class DataIntegrityChecker {
  constructor() {
    this.checksums = new Map();
  }

  // Calculate and store CRC-16 checksum for data
  storeChecksum(dataId, data) {
    const crc16 = this.calculateCRC16(data, 'crc16');
    this.checksums.set(dataId, crc16);
    return crc16;
  }

  // Verify data integrity
  verifyIntegrity(dataId, currentData) {
    const originalCRC = this.checksums.get(dataId);
    if (!originalCRC) {
      return { valid: false, reason: 'Original checksum not found' };
    }

    const currentCRC = this.calculateCRC16(currentData, 'crc16');
    const isValid = originalCRC === currentCRC;

    return {
      valid: isValid,
      originalCRC: '0x' + originalCRC.toString(16).toUpperCase(),
      currentCRC: '0x' + currentCRC.toString(16).toUpperCase(),
      reason: isValid ? 'Data intact' : 'Data has been modified'
    };
  }

  calculateCRC16(data, algorithm) {
    // Use professional CRC library in actual implementation
    return this.crcCalculate(data, algorithm);
  }
}

// Usage example
const checker = new DataIntegrityChecker();

// Store checksum for original data
const originalData = "Important business data";
const checksum = checker.storeChecksum('data001', originalData);
console.log('Stored checksum:', checksum);

// Verify data integrity
const currentData = "Important business data"; // Unmodified
const verification = checker.verifyIntegrity('data001', currentData);
console.log('Integrity verification result:', verification);

2. Communication Protocol Implementation

// Modbus communication protocol CRC verification
class ModbusProtocol {
  constructor() {
    this.crcTable = this.generateCRCTable(0x8005);
  }

  // Generate CRC lookup table
  generateCRCTable(polynomial) {
    const table = [];
    for (let i = 0; i < 256; i++) {
      let crc = i;
      for (let j = 0; j < 8; j++) {
        if (crc & 1) {
          crc = (crc >>> 1) ^ polynomial;
        } else {
          crc = crc >>> 1;
        }
      }
      table[i] = crc & 0xFFFF;
    }
    return table;
  }

  // Calculate Modbus CRC-16
  calculateModbusCRC(data) {
    let crc = 0xFFFF;
    const bytes = typeof data === 'string' ? 
      new TextEncoder().encode(data) : data;

    for (const byte of bytes) {
      const tableIndex = (crc ^ byte) & 0xFF;
      crc = ((crc >>> 8) ^ this.crcTable[tableIndex]) & 0xFFFF;
    }

    return crc;
  }

  // Create Modbus message frame
  createFrame(deviceId, functionCode, data) {
    const frame = [deviceId, functionCode, ...data];
    const crc = this.calculateModbusCRC(new Uint8Array(frame));
    
    // Add CRC in little-endian format to frame end
    frame.push(crc & 0xFF);
    frame.push((crc >>> 8) & 0xFF);
    
    return new Uint8Array(frame);
  }

  // Verify Modbus message frame
  verifyFrame(frame) {
    if (frame.length < 4) {
      return { valid: false, reason: 'Insufficient frame length' };
    }

    const dataLength = frame.length - 2;
    const data = frame.slice(0, dataLength);
    const receivedCRC = frame[dataLength] | (frame[dataLength + 1] << 8);
    const calculatedCRC = this.calculateModbusCRC(data);

    return {
      valid: receivedCRC === calculatedCRC,
      receivedCRC: '0x' + receivedCRC.toString(16).toUpperCase(),
      calculatedCRC: '0x' + calculatedCRC.toString(16).toUpperCase(),
      reason: receivedCRC === calculatedCRC ? 'CRC verification passed' : 'CRC verification failed'
    };
  }
}

// Usage example
const modbus = new ModbusProtocol();

// Create read holding registers request frame
const frame = modbus.createFrame(0x01, 0x03, [0x00, 0x00, 0x00, 0x02]);
console.log('Modbus frame:', Array.from(frame).map(b => '0x' + b.toString(16).toUpperCase()));

// Verify received frame
const verification = modbus.verifyFrame(frame);
console.log('Frame verification result:', verification);

3. File Verification System

// File integrity verification system
class FileIntegritySystem {
  constructor() {
    this.fileChecksums = new Map();
  }

  // Calculate file CRC-16 checksum
  async calculateFileCRC(file, algorithm = 'crc16') {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      
      reader.onload = (event) => {
        try {
          const arrayBuffer = event.target.result;
          const bytes = new Uint8Array(arrayBuffer);
          const crc = this.calculateCRC16(bytes, algorithm);
          
          resolve({
            filename: file.name,
            size: file.size,
            algorithm: algorithm,
            checksum: crc,
            checksumHex: '0x' + crc.toString(16).toUpperCase(),
            timestamp: new Date().toISOString()
          });
        } catch (error) {
          reject(error);
        }
      };
      
      reader.onerror = reject;
      reader.readAsArrayBuffer(file);
    });
  }

  // Batch process files
  async processFiles(files, algorithm = 'crc16') {
    const results = [];
    
    for (const file of files) {
      try {
        const result = await this.calculateFileCRC(file, algorithm);
        results.push(result);
        this.fileChecksums.set(file.name, result);
      } catch (error) {
        results.push({
          filename: file.name,
          error: error.message,
          success: false
        });
      }
    }
    
    return results;
  }

  // Detect duplicate files
  findDuplicates() {
    const checksumMap = new Map();
    const duplicates = [];

    for (const [filename, info] of this.fileChecksums) {
      const key = `${info.checksum}_${info.size}`;
      
      if (checksumMap.has(key)) {
        const existing = checksumMap.get(key);
        duplicates.push({
          group: [existing.filename, filename],
          checksum: info.checksumHex,
          size: info.size
        });
      } else {
        checksumMap.set(key, info);
      }
    }

    return duplicates;
  }

  calculateCRC16(data, algorithm) {
    // Actual CRC-16 calculation implementation
    // Simplified here, use professional library in actual applications
    let crc = algorithm === 'crc16_modbus' ? 0xFFFF : 0x0000;
    const polynomial = algorithm.includes('ccitt') || algorithm.includes('xmodem') ? 0x1021 : 0x8005;
    
    for (const byte of data) {
      crc ^= byte;
      for (let i = 0; i < 8; i++) {
        if (crc & 1) {
          crc = (crc >>> 1) ^ polynomial;
        } else {
          crc = crc >>> 1;
        }
      }
    }
    
    return crc & 0xFFFF;
  }
}

🔍 Algorithm Characteristics

Advantages

  • Fast Calculation: Faster than MD5, SHA algorithms
  • Hardware Friendly: Easy to implement in hardware
  • Standardized: Multiple standard algorithms available
  • Real-time: Suitable for real-time data verification

Limitations

  • Security: Not suitable for cryptographic security
  • Collisions: Different data may have same checksum
  • Length: 16-bit checksum is relatively short

⚠️ Usage Recommendations

  1. Algorithm Selection: Choose appropriate CRC-16 variant based on specific protocol
  2. Performance Optimization: Use lookup tables to improve calculation efficiency
  3. Error Handling: Implement comprehensive error detection and handling
  4. Test Verification: Use standard test vectors to verify implementation correctness

📚 Technical References

  • ITU-T V.41: CCITT CRC-16 standard
  • Modbus Specification: Modbus CRC-16 implementation
  • RFC 1662: CRC-16 usage in PPP
  • ISO 3309: CRC standard in HDLC