I am processing various arrays of UInt8 (little endian) and need to convert them to Int64. In Swift 4 I used
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
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
Is there a way in Swift 5 to convert this without filling the array with additional 0s until the conversion works?
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