There are two ways to go when you google.
extension UInt64{
var uint8Array:[UInt8]{
var x = self.bigEndian
let data = Data(bytes: &x, count: MemoryLayout<UInt64>.size)
return data.map{$0}
}
var uint8Array2:[UInt8]{
var bigEndian:UInt64 = self.bigEndian
let count = MemoryLayout<UInt64>.size
let bytePtr = withUnsafePointer(to: &bigEndian) {
$0.withMemoryRebound(to: UInt8.self, capacity: count) {
UnsafeBufferPointer(start: $0, count: count)
}
}
return Array(bytePtr)
}
}
You will get the same result with either. Since it is a good deal, I also compared the speed.
func testPerformanceUInt64ToUInt8() throws{
let data = (0..<1000000).map{_ in UInt64.random(in: 0..<UInt64.max)}
self.measure {
let uint8s = data.map{$0.uint8Array}
print(uint8s.count)
}
}
func testPerformanceUInt64ToUInt8_2() throws{
let data = (0..<1000000).map{_ in UInt64.random(in: 0..<UInt64.max)}
self.measure {
let uint8s = data.map{$0.uint8Array2}
print(uint8s.count)
}
}
Test Case '[testPerformanceUInt64ToUInt8]'
measured [Time, seconds]
average: 0.176,
relative standard deviation: 9.656%,
values: [0.227525, 0.172769, 0.170525, 0.170571, 0.170574, 0.170578, 0.170615, 0.170248, 0.170302, 0.170817]
Test Case '[testPerformanceUInt64ToUInt8_2]'
measured [Time, seconds]
average: 0.101,
relative standard deviation: 8.491%,
values: [0.126460, 0.098508, 0.098236, 0.097850, 0.097855, 0.097873, 0.097932, 0.097878, 0.097662, 0.097690]
The second one seems to be faster. I find the first way to be easier to understand, but if you need performance, it's better to use the second one.
Recommended Posts