如何快速计算校验和?

时间:2018-10-31 06:25:41

标签: ios swift checksum

我想计算校验和。我预期的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
    }
}

2 个答案:

答案 0 :(得分:1)

进行重写,以避免错误地使用全局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)

答案 1 :(得分:0)

我刚刚从this github link开始扩展,可以在有人需要的情况下获取CRC32校验和。

extension Data {
public func checksum() -> UInt32 {
    let table: [UInt32] = {
        (0...255).map { i -> UInt32 in
            (0..<8).reduce(UInt32(i), { c, _ in
                (c % 2 == 0) ? (c >> 1) : (0xEDB88320 ^ (c >> 1))
            })
        }
    }()
    return ~(self.bytes.reduce(~UInt32(0), { crc, byte in
        (crc >> 8) ^ table[(Int(crc) ^ Int(byte)) & 0xFF]
    }))
} }