Last active
May 9, 2022 10:54
-
-
Save hwaxxer/f540b9caa611fb074462d119ed11a2e8 to your computer and use it in GitHub Desktop.
How to convert hexadecimal string representations to unicode. For example "The 0x1f511 to 0x1f48e is turning 0x1f34b into 0x1f379" becomes "The π to π is turning π into πΉ"
This file contains 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
extension NSString { | |
func stringByConvertingHexToUnicode() -> NSString { | |
var replaced = "" | |
var scanned: NSString? | |
let scanner = NSScanner(string: self as String) | |
while !scanner.atEnd { | |
if scanner.scanUpToString("0x", intoString: &scanned), let s = scanned { | |
replaced.appendContentsOf(s as String) | |
} | |
var scalar: UInt32 = 0 | |
if scanner.scanHexInt(&scalar) && scalar.isValidUnicodeScalar() { | |
let unicodeString = String(UnicodeScalar(scalar)) | |
replaced.appendContentsOf(unicodeString) | |
} | |
} | |
return replaced | |
} | |
} | |
extension UInt32 { | |
func isValidUnicodeScalar() -> Bool { | |
return 0x0000...0xD7FF ~= self || 0xE000...0x10FFFF ~= self | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Glad if you could do its vice versa ??