Skip to content

Instantly share code, notes, and snippets.

@nicklockwood
Last active May 8, 2021 10:54
Show Gist options
  • Save nicklockwood/81b9f122f3db9e7132be7bd61d0c0cea to your computer and use it in GitHub Desktop.
Save nicklockwood/81b9f122f3db9e7132be7bd61d0c0cea to your computer and use it in GitHub Desktop.
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
}
}
@nicklockwood
Copy link
Author

nicklockwood commented Apr 14, 2021

From my own timings, popping a substring is slower than using index.after(). Not sure how it compares to iterator: https://twitter.com/nicklockwood/status/1382142248247308292

@mayoff
Copy link

mayoff commented Apr 14, 2021

Try using hexString.utf8.withContiguousStorageIfAvailable. You'll have to write your own hexDigitValue though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment