swift - swift 将 UInt32 拆分为 [UInt8]

标签 swift bitwise-operators

我想将 UInt32 添加到我使用 [UInt8] 的字节缓冲区。在 java 中,有一个方便的 ByteBuffer 类,它具有 putInt() 之类的方法,完全适用于这种情况。这怎么能 swift 完成?

我想我可以按如下方式解决这个问题:

let example: UInt32 = 72 << 24 | 66 << 16 | 1 << 8 | 15
var byteArray = [UInt8](count: 4, repeatedValue: 0)

for i in 0...3 {
    byteArray[i] = UInt8(0x0000FF & example >> UInt32((3 - i) * 8))
}

虽然这很冗长,但有更简单的方法吗?

最佳答案

你的循环可以更简洁地写成

let byteArray = 24.stride(through: 0, by: -8).map {
    UInt8(truncatingBitPattern: example >> UInt32($0))
}

或者,创建一个 UnsafeBufferPointer 并将其转换 到数组:

let example: UInt32 = 72 << 24 | 66 << 16 | 1 << 8 | 15

var bigEndian = example.bigEndian
let bytePtr = withUnsafePointer(&bigEndian) {
    UnsafeBufferPointer<UInt8>(start: UnsafePointer($0), count: sizeofValue(bigEndian))
}
let byteArray = Array(bytePtr)

print(byteArray) // [72, 66, 1, 15]

Swift 3 更新(Xcode 8 beta 6):

var bigEndian = example.bigEndian
let count = MemoryLayout<UInt32>.size
let bytePtr = withUnsafePointer(to: &bigEndian) {
    $0.withMemoryRebound(to: UInt8.self, capacity: count) {
        UnsafeBufferPointer(start: $0, count: count)
    }
}
let byteArray = Array(bytePtr)

关于swift - swift 将 UInt32 拆分为 [UInt8],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29970204/

相关文章:

Java按位&运算符多重权限

lua - 如何在Lua中使用按位运算符XOR?

python - 按位循环右移

ios - 缩放受约束的 SCNNode

ios - Swift 3 转换器添加了 fileprivate 函数

ios - iOS 中的 NSShadow set() 方法

Javascript 按位运算符 - 需要解释

c++ - 在不截断的情况下撤消类次

ios - 位置管理器 :didRangeBeacons not detect the same beacon two times

ios - 使用协议(protocol)对类似的 UITableViewCell 进行分组以减少代码