1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Swift] UInt64型の整数を[UInt8]に変換する

Last updated at Posted at 2020-09-28

ググると二つの方法が出てきます。

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)
    }
}

どっちでも同じ結果が得られます。折角なので速度も比較してみました。

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]

二つ目の方が速度は速そうです。一つ目の書き方の方が分かりやすいと感じますが、パフォーマンスが必要な場面では二つ目を使った方がいいでしょう。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?