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())
}
https://stackoverflow.com/a/42731691/6570300
Recommended Posts