在Swift中将bytes / Uint8数组转换为Int
问题描述:
如何将4字节数组转换为相应的Int?
How to convert a 4-bytes array into the corresponding Int?
let array: [UInt8] ==> let value : Int
示例:
\0\0\0\x0e
输出:
Output:
14
我在互联网上找到的一些代码不起作用:
Some code I found on the internet that doesn't work:
let data = NSData(bytes: array, length: 4)
data.getBytes(&size, length: 4)
// the output to size is 184549376
答
有两个问题:
-
Int
是64位平台上的64位整数,输入数据
只有32位。 -
Int
在所有当前的Swift平台上使用little-endian表示,
你的输入是big-endian。
-
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.
据说以下情况可行:
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
或者在Swift 3中使用数据
:
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 })
使用一些缓冲区指针魔术,你可以避免中间
复制到 NSData
对象(Swift 2):
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
对于此方法的Swift 3版本,请参阅环境光的答案。
For a Swift 3 version of this approach, see ambientlight's answer.