在 Swift 中将 bytes/UInt8 数组转换为 Int [英] Convert bytes/UInt8 array to Int in Swift

查看:62
本文介绍了在 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.

这篇关于在 Swift 中将 bytes/UInt8 数组转换为 Int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆