Skip to content

Instantly share code, notes, and snippets.

@alexbosworth
Created January 12, 2017 17:03
Show Gist options
  • Save alexbosworth/8a74b705ad26d283e5c65f66ecd6f24b to your computer and use it in GitHub Desktop.
Save alexbosworth/8a74b705ad26d283e5c65f66ecd6f24b to your computer and use it in GitHub Desktop.
/** Extensions to Data
*/
extension Data {
/** Create data from hex string
*/
init(hex: String) throws {
var bytes = Array<Byte>(repeating: Byte(), count: (hex.unicodeScalars.count + 1) >> 1)
try hex.unicodeScalars.enumerated().forEach { index, scalar in
var nibble = try scalar.hexNibble()
if index & 1 == 0 { nibble <<= 4 }
bytes[index >> 1] |= nibble
}
self = Data(bytes: bytes)
}
/** Returns data represented as a hex encoded string
*/
var hexEncoded: String { return map { String(format: "%02hhx", $0) }.joined() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment