我想计算校验和。我预期的crc答案是0xE1
但是,当我运行此代码时,它返回0。我没有任何解决方案可以做到这一点。请帮我解决这个问题。
以下是我尝试过的代码。

我的viewController:

    class ViewController: UIViewController {
    var checkSum:UInt8 = 0
    override func viewDidLoad() {
            super.viewDidLoad()
    let bytes = [0x01,0x0B,0x00,0x0B,0x03,0x07,0x12,0x0E,0x0C,0x10,0x09,0x12,0x0C,0x19,0x09,0xFF,0x14]
        for item in bytes {
            print(calculateCheckSum(crc: checkSum, byteValue: UInt8(item)))
        }
    }

func calculateCheckSum(crc:UInt8, byteValue: UInt8) -> UInt8 {

        let generator = 0x1D

        checkSum = crc ^ byteValue

        for _ in 1...8 {
            if (crc & 0x80 != 0) {
                checkSum = (crc << 1) ^ UInt8(Int8(generator))
            }
            else {
                checkSum <<= UInt8(1)
            }
        }
        return crc
    }
}

最佳答案

重写以免错误使用全局checkSum变量。

func calculateCheckSum(crc:UInt8, byteValue: UInt8) -> UInt8 {
    let generator: UInt8 = 0x1D

    // a new variable has to be declared inside this function
    var newCrc = crc ^ byteValue

    for _ in 1...8 {
        if newCrc & 0x80 != 0 {
            newCrc = (newCrc << 1) ^ generator
        }
        else {
            newCrc <<= 1
        }
    }
    return newCrc
}

另外,似乎您没有正确使用方法的结果:
var checkSum: UInt8 = 0
let bytes = [...]
for item in bytes {
   checkSum = calculateCheckSum(crc: checkSum, byteValue: UInt8(item))
}

print(checkSum)

10-01 21:46