我需要將這個帶有內部函式的 c 標頭轉換為 swift 腳本。我這樣做了,但是當我嘗試這兩個函式并比較結果時,它們結果是不相等的。到底是怎么回事?我想我已經把它縮小到:這可能是關于指標在 swift 中很奇怪。
C 標頭: ( header.h) (不是我的。請參閱 PGPFormat)
#define CRC24_INIT 0xB704CEL
#define CRC24_POLY 0x1864CFBL
long crc_octets_1(unsigned char *octets, long len)
{
long crc = CRC24_INIT;
int i;
while (len) {
crc ^= (*octets ) << 16;
for (i = 0; i < 8; i ) {
crc <<= 1;
if (crc & 0x1000000)
crc ^= CRC24_POLY;
}
len-=1;
}
return crc & 0xFFFFFFL;
}
我的快速選擇:
let CRC24_INIT_: Int = 0xB704CE
let CRC24_POLY_: Int = 0x1864CFB
func crc_octets_1( _ octets: UnsafeMutablePointer<UInt8>, _ len: Int) -> Int {
var octets2 = octets
var crc = CRC24_INIT;
var l=len
while (l != 0) {
octets2 = 1 //i have also tried incrementing the actual value that is being pointed to. It still doesn't work. I have also tried urinary
crc ^= Int(octets2.pointee) << 16;
for _ in 0..<8 {
crc <<= 1;
if ((crc & 0x1000000) != 0) {
crc ^= CRC24_POLY;
}
}
l -= 1
}
return crc & 0xFFFFFF;
}
最后一個考試
func test() {
var dataBytes: [UInt8] = [1,2,3,4,5]
let checksum1 = crc_octets_1(&dataBytes, dataBytes.count)
let checksum2 = crc_octets_2(&dataBytes, dataBytes.count)
XCTAssertEqual(checksum1, checksum2)
}
這是我得到的回報: XCTAssertEqual failed: ("3153197") is not equal to ("1890961")
uj5u.com熱心網友回復:
正如 Rob Napier 指出的那樣,問題在于你在哪里增加octets2. Objective-C 在檢索到值后遞增指標,而 Swift 版本在之前遞增它。
但我可能會更進一步,完全消除不安全指標 ( octetsand octets2) 以及lenandl變數。相反,只需dataBytes直接傳遞陣列:
func crc(for bytes: [UInt8]) -> Int {
var crc = CRC24_INIT
for byte in bytes {
crc ^= Int(byte) << 16
for _ in 0..<8 {
crc <<= 1
if (crc & 0x1000000) != 0 {
crc ^= CRC24_POLY
}
}
}
return crc & 0xFFFFFF
}
或者,如果你想變得花哨,你可以做一個通用的再現,而不是接受任何Sequence一個UInt8(即,一個[UInt8]陣列或一個Data):
func crc<T>(for bytes: T) -> Int where T: Sequence, T.Element == UInt8 {
var crc = CRC24_INIT
for byte in bytes {
crc ^= Int(byte) << 16
for _ in 0..<8 {
crc <<= 1
if (crc & 0x1000000) != 0 {
crc ^= CRC24_POLY
}
}
}
return crc & 0xFFFFFF
}
然后您可以執行以下任一操作:
let dataBytes: [UInt8] = ...
let checksum1 = crc(for: dataBytes) // 1890961
或者
let data: Data = ...
let checksum2 = crc(for: data) // 1890961
在上面,我還洗掉了分號并使用了更快捷的方法命名約定。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408325.html
標籤:
下一篇:我不明白指標的行為
