Your loop can more compactly be written as
let byteArray = 24.stride(through: 0, by: -8).map {
UInt8(truncatingBitPattern: example >> UInt32($0))
}
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]
Update for 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)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…