[Swift] Convert ByteArray and HexString to each other

Implementation

String+.swift


extension String {
    func toBytes() -> [UInt8]? {
        let length = count
        if length & 1 != 0 {
            return nil
        }
        var bytes = [UInt8]()
        bytes.reserveCapacity(length / 2)
        var index = startIndex
        for _ in 0..<length / 2 {
            let nextIndex = self.index(index, offsetBy: 2)
            if let b = UInt8(self[index..<nextIndex], radix: 16) {
                bytes.append(b)
            } else {
                return nil
            }
            index = nextIndex
        }
        return bytes
    }
}

Data+.swift


extension Data {
    func toHexString() -> String {
        var hexString = ""
        for index in 0..<count {
            hexString += String(format: "%02X", self[index])
        }
        return hexString
    }
}

Operation check

Test.swift


func testBytesHexConversion() {
    let bytes: [UInt8] = [0, 1, 254, 255]
    XCTAssertEqual("0001FEFF", Data(bytes).toHexString())
    XCTAssertEqual(bytes, "0001FEFF".toBytes())
}

reference

https://stackoverflow.com/a/42731691/6570300

Recommended Posts

[Swift] Convert ByteArray and HexString to each other
How to convert LocalDate and Timestamp
Convert Swift 2D array to C 2D array
Convert JSON to TSV and TSV to JSON with Ruby
[Ruby] How to convert from lowercase to uppercase and from uppercase to lowercase
Convert from C String pointer to Swift String type
Convert a string to a character-by-character array with swift
Ruby How to convert between uppercase and lowercase
<java> Read Zip file and convert directly to string
Convert Java enum enums and JSON to and from Jackson
[Java] Convert character strings to uppercase / lowercase (AOJ⑨-swap uppercase and lowercase)
Convert the array of errors.full_messages to characters and output
How to convert A to a and a to A using AND and OR in Java
[Java] Convert JSON to Java and Java to JSON-How to use GSON and Jackson-