Reputation: 36
I receive a line in the format "iso-8859-5", but I can not decode it correctly. I think the problem is that I'm not converting the string correctly to data. But I do not know how to correctly convert a string to a data, without using a encoding.
Please help.
let string = "\\X2\\041F043504400435043A0440044B044204380435\\X0\\:\\X2\\042D\\X0\\_\\X2\\041F043B043804420430\\X0\\"
let encodingName = "iso-8859-5"
let cfe = CFStringConvertIANACharSetNameToEncoding(encodingName as CFString!)
if cfe != kCFStringEncodingInvalidId {
let encoding = CFStringConvertEncodingToNSStringEncoding(cfe)
let decString: String = NSString(data: string.data(using: String.Encoding.utf8)!, encoding: String.Encoding(rawValue: UInt(encoding)).rawValue)! as String
print("string: " + decString)
}
Upvotes: 1
Views: 903
Reputation: 17844
Your encoded string consists of sequences 16-bit Unicode values (the hex digits between the \X2\
and \X0
separators). When you extract the values from that, you'll get this:
let bytes = [ 0x041F, 0x0435, 0x0440, 0x0435, 0x043A, 0x0440, 0x044B, 0x0442, 0x0438, 0x0435 ]
which you can convert to a String using this:
var s = ""
s.unicodeScalars.append(contentsOf: bytes.flatMap { UnicodeScalar($0) } )
print(s) // prints "Перекрытие"
Upvotes: 1
Reputation: 385500
You can't stick arbitrary bytes into a string literal in Swift. You need to store it as a array of UInt8
or as a Data
. Example:
let bytes: [UInt8] = [0x41, 0xF0, 0x43, 0x50, 0x44, 0x43, 0x50, 0x43, 0xA0, 0x44]
let data = Data(bytes)
let cfEncoding = CFStringConvertIANACharSetNameToEncoding("iso-8859-5" as CFString)
let nsEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding)
let string = NSString(data: data, encoding: nsEncoding) as String
Upvotes: 1