Created
August 26, 2015 15:09
-
-
Save joltguy/a21277b8e598f81d2b22 to your computer and use it in GitHub Desktop.
Handy little Swift extensions for String and Int to simplify notation conversion
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
// A slick little number conversion extension | |
// Original source: http://stackoverflow.com/a/26811354/771460 | |
extension String { | |
var hexToInt : Int { return Int(strtoul(self, nil, 16)) } | |
var hexToDouble : Double { return Double(strtoul(self, nil, 16)) } | |
var hexToBinary : String { return String(hexToInt, radix: 2) } | |
var intToHex : String { return String(toInt()!, radix: 16) } | |
var intToBinary : String { return String(toInt()!, radix: 2) } | |
var binaryToInt : Int { return Int(strtoul(self, nil, 2)) } | |
var binaryToDouble : Double { return Double(strtoul(self, nil, 2)) } | |
var binaryToHex : String { return String(binaryToInt, radix: 16) } | |
} | |
extension Int { | |
var binaryString: String { return String(self, radix: 2) } | |
var hexString : String { return String(self, radix: 16) } | |
var doubleValue : Double { return Double(self) } | |
} | |
/* Examples ---- | |
"ff".hexToInt // "255" | |
"ff".hexToDouble // "255.0" | |
"ff".hexToBinary // "11111111" | |
"255".intToHex // "ff" | |
"255".intToBinary // "11111111" | |
"11111111".binaryToInt // "255" | |
"11111111".binaryToDouble // "255.0" | |
"11111111".binaryToHex // "ff" | |
255.binaryString // "11111111" | |
255.hexString // "ff" | |
255.doubleValue // 255.0 | |
---- */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment