4

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!

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Mike Nathas
  • 1,247
  • 2
  • 11
  • 29

2 Answers2

4

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
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
3

withUnsafeBytes { $0.load works only if the array contains exactly 64 bit (8 bytes) for example

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

var raw : Int64 = 0
withUnsafeMutableBytes(of: &raw, { array.copyBytes(to: $0)} )
print(raw)
vadian
  • 274,689
  • 30
  • 353
  • 361