Created
January 12, 2017 17:03
-
-
Save alexbosworth/8a74b705ad26d283e5c65f66ecd6f24b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** 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