快速将UInt32拆分为[UInt8] [英] Split UInt32 into [UInt8] in swift
本文介绍了快速将UInt32拆分为[UInt8]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将 UInt32
添加到我使用 [UInt8]
的字节缓冲区中.在Java中,有一个方便的ByteBuffer类,它具有类似putInt()的方法,用于完全一样的情况.怎么能迅速做到这一点?
I want to add UInt32
to byte buffer for which I use [UInt8]
. In java, there is convenient ByteBuffer class that has methods like putInt() for cases exactly like this. How could this be done in swift?
我想我可以解决以下问题:
I guess I could solve this as following:
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))
}
这是很冗长,更简单的方法吗?
This is quite verbose though, any simpler way?
推荐答案
您的循环可以更紧凑地写为
Your loop can more compactly be written as
let byteArray = 24.stride(through: 0, by: -8).map {
UInt8(truncatingBitPattern: example >> UInt32($0))
}
或者,创建一个 UnsafeBufferPointer
并将其转换到数组:
Alternatively, create an UnsafeBufferPointer
and convert that
to an array:
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)
这篇关于快速将UInt32拆分为[UInt8]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文