[Swift] Mutual conversion between Int and Data

We have confirmed the operation with Swift5.

Implementation

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

test

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

reference

Recommended Posts

[Swift] Mutual conversion between Int and Data
Mutual conversion between Function and Consumer
Hex and UIColor mutual conversion in Swift
Mutual conversion between Java objects and JSON using Moshi
Difference between int and Integer in Java
Summary of mutual conversion between Groovy's Default Groovy Methods and Java's Stream API
[Swift] UITextField taught me the difference between nil and ""
Switch between JDK 7 and JDK 8
[Swift] Constants and variables
Difference between vh and%
Difference between i ++ and ++ i