Skip to content

Instantly share code, notes, and snippets.

@mjmsmith
Created July 18, 2017 20:10
Show Gist options
  • Save mjmsmith/57244bc7fd4a6ee6eb0714d07f59bb15 to your computer and use it in GitHub Desktop.
Save mjmsmith/57244bc7fd4a6ee6eb0714d07f59bb15 to your computer and use it in GitHub Desktop.
import Foundation
extension Data {
public init?(hexString: String) {
let utf16 = hexString.utf16
var data = Data(capacity: utf16.count / 2)
var hiIndex = utf16.startIndex
while hiIndex != utf16.endIndex {
guard let hi = Data.decodeNibble(utf16[hiIndex]),
let loIndex = utf16.index(hiIndex, offsetBy: 1, limitedBy: utf16.endIndex),
let lo = Data.decodeNibble(utf16[loIndex]) else {
return nil
}
var value = (hi << 4) + lo
data.append(&value, count: 1)
hiIndex = utf16.index(hiIndex, offsetBy: 2, limitedBy: utf16.endIndex) ?? utf16.endIndex
}
self = data
}
public func hexString() -> String {
return self.withUnsafeBytes() { (bytes: UnsafePointer<UInt8>) in
var string = ""
for i in 0..<self.count {
string += String(format: "%02x", bytes[i])
}
return string
}
}
fileprivate static func decodeNibble(_ u: UInt16) -> UInt8? {
switch u {
case 0x30...0x39:
return UInt8(u - 0x30)
case 0x41...0x46:
return UInt8(u - 0x41 + 0x0a)
case 0x61...0x66:
return UInt8(u - 0x61 + 0x0a)
default:
return nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment