Last active
July 19, 2016 15:08
-
-
Save mluisbrown/bdf38d7a9b291aaa9e352a44f0cb6aee to your computer and use it in GitHub Desktop.
UTF16 encode and decode
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
import Foundation | |
func encodeString(str: String) -> String { | |
return Array(str.utf16).map { | |
String(format: "%04x", $0) | |
}.reduce("") { | |
return $0 + $1 | |
} | |
} | |
func decodeString(encoded: String) -> String { | |
var utf16Array = [UInt16]() | |
0.stride(to: encoded.characters.count, by: 4).forEach { | |
let startIndex = encoded.characters.startIndex.advancedBy($0) | |
let endIndex = encoded.characters.startIndex.advancedBy($0 + 3) | |
let hex4 = encoded.substringWithRange(startIndex...endIndex) | |
utf16Array.append(UInt16(hex4, radix: 16)!) | |
} | |
return String(utf16CodeUnits: utf16Array, count: utf16Array.count) | |
} | |
let str = "Hello, Playground" | |
let encoded = encodeString(str) | |
let decoded = decodeString(encoded) | |
print(encoded) | |
print(decoded) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment