Skip to content

Instantly share code, notes, and snippets.

@alexbosworth
Created January 12, 2017 16:59
Show Gist options
  • Save alexbosworth/20c270487deb2c9ef8576f971548238d to your computer and use it in GitHub Desktop.
Save alexbosworth/20c270487deb2c9ef8576f971548238d to your computer and use it in GitHub Desktop.
/** Extensions to UnicodeScalar
*/
extension UnicodeScalar {
/** Unicode scalar errors
*/
enum UnicodeScalarError: String, Error {
case illegalHexValue
}
/** Get the byte value of a hex nibble
*/
func hexNibble() throws -> Byte {
switch self {
case UnicodeScalar(unicodeScalarLiteral:"0")...UnicodeScalar(unicodeScalarLiteral:"9"):
return Byte(self.value - UnicodeScalar(unicodeScalarLiteral:"0").value)
case UnicodeScalar(unicodeScalarLiteral:"a")...UnicodeScalar(unicodeScalarLiteral:"f"):
return Byte(self.value - UnicodeScalar(unicodeScalarLiteral:"a").value + 0xa)
case UnicodeScalar(unicodeScalarLiteral:"A")...UnicodeScalar(unicodeScalarLiteral:"F"):
return Byte(self.value - UnicodeScalar(unicodeScalarLiteral:"A").value + 0xa)
default:
throw UnicodeScalarError.illegalHexValue
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment