CRC-16/CCITT 在 Swift 4
CRC-16/CCITT in Swift 4
如何使此代码在 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{[=12=]}) == 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'
您可以使用 UInt16(byte)
而不是 UInt32(byte)
如何使此代码在 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{[=12=]}) == 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'
您可以使用 UInt16(byte)
而不是 UInt32(byte)