Jerry Jerry - 2 months ago 20
Swift Question

Convert bytes/Uint8 array to Int in Swift

How to convert a 4 types/Uint8 array into its corresponding Int

let array: [UInt8] ==> let value : Int

Example:

Input: \0\0\0\x0e

Output: 14

Some code I found on the internet doesn't work

let data = NSData(bytes: array, length: 4)
data.getBytes(&size, length: 4)
// the output to size is 184549376

Answer

There are two problems:

  • Int is a 64-bit integer on 64-bit platforms, your input data has only 32-bit.
  • Int uses a little-endian representation on all current Swift platforms, your input is big-endian.

That being said the following would work:

let array : [UInt8] = [0, 0, 0, 0x0E]
var value : UInt32 = 0
let data = NSData(bytes: array, length: 4)
data.getBytes(&value, length: 4)
value = UInt32(bigEndian: value)

print(value) // 14

With some buffer pointer magic you can avoid the intermediate copy to an NSData object:

let array : [UInt8] = [0, 0, 0, 0x0E]
var value = array.withUnsafeBufferPointer({ 
     UnsafePointer<UInt32>($0.baseAddress).memory
})
value = UInt32(bigEndian: value)

print(value) // 14