如何将一个4字节的数组转换为相应的Int?
let array: [UInt8] ==> let value : Int
例:
\0\0\0\x0e
14
let data = NSData(bytes: array, length: 4) data.getBytes(&size, length: 4) // the output to size is 184549376
有两个问题:
Int
话虽如此,以下方法会起作用:
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
或Data在Swift 3中使用:
Data
let array : [UInt8] = [0, 0, 0, 0x0E] let data = Data(bytes: array) let value = UInt32(bigEndian: data.withUnsafeBytes { $0.pointee })
使用一些缓冲区指针魔术,您可以避免中间复制到NSData对象(Swift 2):
NSData
let array : [UInt8] = [0, 0, 0, 0x0E] var value = array.withUnsafeBufferPointer({ UnsafePointer<UInt32>($0.baseAddress).memory }) value = UInt32(bigEndian: value) print(value) // 14
有关此方法的Swift 3版本,请参见环境光的答案。