5
5

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 その2Advent Calendar 2020

Day 22

[Swift] IntとDataの相互変換

Last updated at Posted at 2020-12-22

Swift5で動作確認をしています。

実装

Int+Data.swift
import Foundation

extension Int {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<Int>.size).reversedData
    }
}

extension UInt8 {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<UInt8>.size).reversedData
    }
}

extension UInt16 {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<UInt16>.size).reversedData
    }
}

extension UInt32 {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<UInt32>.size).reversedData
    }
}

extension UInt64 {
    var data: Data {
        var int = self
        return Data(bytes: &int, count: MemoryLayout<UInt64>.size).reversedData
    }
}
Data+Int.swift
import Foundation

extension Data {
    var reversedBytes: [UInt8] {
        var values = [UInt8](repeating: 0, count: count)
        copyBytes(to: &values, count: count)
        return values.reversed()
    }

    var reversedData: Data {
        return Data(bytes: reversedBytes, count: count)
    }

    var uint8: UInt8 {
        UInt8(bigEndian: withUnsafeBytes { $0.load(as: UInt8.self) })
    }

    var uint16: UInt16 {
        UInt16(bigEndian: withUnsafeBytes { $0.load(as: UInt16.self) })
    }

    var uint32: UInt32 {
        UInt32(bigEndian: withUnsafeBytes { $0.load(as: UInt32.self) })
    }

    var uint64: UInt64 {
        UInt64(bigEndian: withUnsafeBytes { $0.load(as: UInt64.self) })
    }
}

テスト

Int+DataTest.swift
final class IntPlusDataTest: XCTestCase {
    func testToData() {
        XCTAssertEqual(123_456, 123_456.data.uint64)
        XCTAssertEqual(10, UInt8(10).data.uint8)
        XCTAssertEqual(1234, UInt16(1234).data.uint16)
        XCTAssertEqual(123_456, UInt32(123_456).data.uint32)
        XCTAssertEqual(4_294_967_295_000, UInt64(4_294_967_295_000).data.uint64)
    }
}

参考

5
5
2

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
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?