Swift 4中的CRC-16 / CCITT

时间:2018-03-03 21:43:18

标签: swift swift4 crc16

如何让这段代码在swift 4中运行:

    func crc16ccitt(data: [UInt8],seed: UInt16 = 0x1d0f, final: UInt16 = 0xffff)->UInt16{
    var crc = seed
    data.forEach { (byte) in
        crc ^= UInt32(byte) << 8
        (0..<8).forEach({ _ in
            crc = (crc & UInt32(0x8000)) != 0 ? (crc << 1) ^ 0x1021 : crc << 1
        })
    }
    return UInt16(crc & final)
}
print(crc16ccitt(data: "Karim".utf8.map{$0}) == 0x792C)

我收到2个错误:

"Binary operator'^=' cannot be applied to operands of type 'UInt16' and 'UInt32'

"Binary operator'&' cannot be applied to operands of type 'UInt16' and 'UInt32'

1 个答案:

答案 0 :(得分:4)

您可以使用UInt16(byte)代替UInt32(byte)