Last active
May 8, 2021 10:54
-
-
Save nicklockwood/81b9f122f3db9e7132be7bd61d0c0cea to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Data { | |
init?(hexString: String) { | |
let count = hexString.count / 2 | |
var data = Data(capacity: count) | |
var i = hexString.startIndex | |
for _ in 0 ..< count { | |
let j = hexString.index(after: i) | |
if var byte = UInt8(hexString[i ... j], radix: 16) { | |
data.append(&byte, count: 1) | |
} else { | |
return nil | |
} | |
i = hexString.index(after: j) | |
} | |
self = data | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Try using
hexString.utf8.withContiguousStorageIfAvailable
. You'll have to write your ownhexDigitValue
though.