search
LoginSignup
5

More than 1 year has passed since last update.

posted at

updated at

Organization

[Swift] IntとDataの相互変換

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

参考

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
What you can do with signing up
5