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

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

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

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