在 Swift 中将 bytes/UInt8 数组转换为 Int

在 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

输出:

14

我在互联网上发现的一些不起作用的代码:

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

有两个问题:

  • Int 是 64 位平台上的 64 位整数,您的输入数据只有 32 位.
  • Int 在当前所有 Swift 平台上使用小端表示,您的输入是大端的.
  • 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

或者在 Swift 3 中使用 Data:

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.