Swift 4下CRC-16/CCITT代码报错求助:如何解决两处错误?
Hey there! Based on common pitfalls developers hit with CRC-16/CCITT in Swift 4, those two errors are almost certainly related to incorrect initial register setup or flawed bitwise logic. Let's break down the fixes and share a working implementation.
Common Error Scenarios & Fixes
Error 1: Wrong Initial Value or Type Overflow
A lot of folks use 0x0000 as the initial CRC value, but CRC-16/CCITT requires 0xFFFF as the standard starting point. Also, using Int instead of UInt16 for the CRC register can lead to unexpected overflow behavior in Swift 4's strict type system.
Error 2: Misaligned Byte/Bit Operations
Another frequent mistake is mishandling how bytes are shifted or XORed. For CRC-16/CCITT, you need to left-shift each byte by 8 bits before XORing with the CRC register, then iterate through each bit to apply the polynomial.
Working Swift 4 Implementation
Here's a tested, error-free implementation as an extension on Data (super convenient for real-world use):
import Foundation extension Data { func crc16CCITT() -> UInt16 { let polynomial: UInt16 = 0x1021 // Standard CRC-16/CCITT polynomial var crc: UInt16 = 0xFFFF // Correct initial value for byte in self { // Shift byte left 8 bits and XOR with current CRC crc ^= UInt16(byte) << 8 // Iterate through each bit of the byte for _ in 0..<8 { if crc & 0x8000 != 0 { crc = (crc << 1) ^ polynomial } else { crc <<= 1 } } } return crc } } // Example usage let testString = "Hello World" guard let testData = testString.data(using: .utf8) else { fatalError("Failed to convert string to data") } let crcResult = testData.crc16CCITT() print(String(format: "CRC-16/CCITT Result: 0x%04X", crcResult)) // Should output 0x397B
Key Fixes Explained
- Correct Initial Value: Using
0xFFFFaligns with CRC-16/CCITT specifications, fixing the first common error. - Type Safety: Sticking to
UInt16for the CRC register prevents overflow issues that come with signed integer types. - Proper Bitwise Flow: The shift-and-XOR sequence matches the standard CRC-16/CCITT algorithm, eliminating logic errors.
If your original code had other specific issues (like using Swift 5-only syntax in Swift 4), let me know—but this implementation should resolve the two most prevalent problems.
内容的提问来源于stack exchange,提问作者Somebody

