0
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] ByteArrayとHexStringを相互変換する

Posted at

実装

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

動作確認

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

参考

0
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
0
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?