Created
January 12, 2017 16:59
-
-
Save alexbosworth/20c270487deb2c9ef8576f971548238d 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 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