Skip to content

Instantly share code, notes, and snippets.

@hwaxxer
Last active May 9, 2022 10:54
Show Gist options
  • Save hwaxxer/f540b9caa611fb074462d119ed11a2e8 to your computer and use it in GitHub Desktop.
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 🍹"
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
}
}
@dheerajFortees
Copy link

dheerajFortees commented May 9, 2022

Glad if you could do its vice versa ??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment