Convert bytes/UInt8 array to Int in Swift
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
Or using Data
in Swift 3:
let array : [UInt8] = [0, 0, 0, 0x0E]
let data = Data(bytes: array)
let value = UInt32(bigEndian: data.withUnsafeBytes { $0.pointee })
With some buffer pointer magic you can avoid the intermediate
copy to an NSData
object (Swift 2):
let array : [UInt8] = [0, 0, 0, 0x0E]
var value = array.withUnsafeBufferPointer({
UnsafePointer<UInt32>($0.baseAddress).memory
})
value = UInt32(bigEndian: value)
print(value) // 14
For a Swift 3 version of this approach, see ambientlight's answer.
In Swift 3 it is now a bit more wordy:
let array : [UInt8] = [0, 0, 0, 0x0E]
let bigEndianValue = array.withUnsafeBufferPointer {
($0.baseAddress!.withMemoryRebound(to: UInt32.self, capacity: 1) { $0 })
}.pointee
let value = UInt32(bigEndian: bigEndianValue)
I think Martin's answer is better than this, but I still want to post mine. Any suggestion would be really helpful.
let array : [UInt8] = [0, 0, 0, 0x0E]
var value : Int = 0
for byte in array {
value = value << 8
value = value | Int(byte)
}
print(value) // 14