Skip to content

Instantly share code, notes, and snippets.

@krzyzanowskim
Last active March 7, 2022 23:09
Show Gist options
  • Save krzyzanowskim/2fabe6f9d6735814f4ed9e20828a4b09 to your computer and use it in GitHub Desktop.
Save krzyzanowskim/2fabe6f9d6735814f4ed9e20828a4b09 to your computer and use it in GitHub Desktop.
Creates a string from the given bytes in the UTF16 encoding.
extension String {
/// Creates a string from the given bytes in the specified encoding.
init<C>(decoding bytes: C, as sourceEncoding: UTF16.Type) where C : Collection, C.Element == UInt8, C.Index == Int {
let codeUnits = stride(from: bytes.startIndex, to: bytes.endIndex, by: MemoryLayout<UTF16.CodeUnit>.stride).map { index -> UTF16.CodeUnit in
UTF16.CodeUnit(bytes[index]) | (UTF16.CodeUnit(bytes[index.advanced(by: 1)]) &<< 8)
}
self.init(decoding: codeUnits, as: sourceEncoding)
}
}
// let bytes: [UInt8] = [97, 0, 98, 0, 99, 0, 100, 0, 5, 1]
// let string = String(decoding: bytes, as: UTF16.self)
// string == "abcdą"
extension Array where Element == UInt16 {
/// Little-Endian UTF16 bytes
var bytes: [UInt8] {
flatMap {
[
UInt8($0.littleEndian & 0xFF),
UInt8(($0.littleEndian &>> 8) & 0xFF)
]
}
}
}
extension String.UTF16View {
/// Little-Endian UTF16 bytes
var bytes: [UInt8] {
Array(self).bytes
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment