gpt4 book ai didi

swift - swift 将 UInt32 拆分为 [UInt8]

转载 作者:搜寻专家 更新时间:2023-10-30 21:49:13 28 4
gpt4 key购买 nike

我想将 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com