Search code examples
iosswiftstringdecoding

Swift, decoding "iso-8859-5"


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)
}

Solution

  • 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 "Перекрытие"