简体   繁体   English

在Swift 5中将字节数组转换为Int64

[英]Convert array of bytes to Int64 in Swift 5

I am processing various arrays of UInt8 (little endian) and need to convert them to Int64. 我正在处理UInt8(小尾数)的各种数组,需要将它们转换为Int64。 In Swift 4 I used 在Swift 4中,我使用了

let array: [UInt8] = [13,164,167,80,4,0]
let raw = Int64(littleEndian: Data(array).withUnsafeBytes { $0.pointee })
print(raw) //18533032973

which worked fine. 效果很好。 However in Swift 5 this way is deprecated so I switched to 但是在Swift 5中不赞成这种方式,所以我切换到

let array: [UInt8] = [13,164,167,80,4,0]
let raw = array.withUnsafeBytes { $0.load(as: Int64.self) }
print(raw)

which gives an error message: 给出错误信息:

Fatal error: UnsafeRawBufferPointer.load out of bounds 致命错误:UnsafeRawBufferPointer.load超出范围

Is there a way in Swift 5 to convert this without filling the array with additional 0s until the conversion works? 在Swift 5中,有没有一种方法可以在不转换数组的情况下将其转换为0,直到转换成功?

Thanks! 谢谢!

Alternatively you can compute the number by repeated shifting and adding, as suggested in the comments: 或者,您可以通过重复移位和添加来计算数字,如注释中所建议:

let array: [UInt8] = [13, 164, 167, 80, 4, 0]
let raw = array.reversed().reduce(0) { $0 << 8 + UInt64($1) }
print(raw) // 18533032973

withUnsafeBytes { $0.load works only if the array contains exactly 64 bit (8 bytes) for example withUnsafeBytes { $0.load仅在数组包含正好64位(8字节)的情况下有效

let array: [UInt8] = [13,164,167,80,4,0,0,0]
let raw = array.withUnsafeBytes { $0.load(as: Int64.self) }
print(raw)

With your 6 bytes array you can use 使用6个字节的数组,您可以使用

var raw : Int64 = 0
withUnsafeMutableBytes(of: &raw, { array.copyBytes(to: $0)} )
print(raw)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM