我收到格式" iso-8859-5"的一行,但我无法正确解码。我认为问题在于我没有正确地将字符串转换为数据。但我不知道如何正确地将字符串转换为数据,而不使用编码。
请帮忙。
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)
}
答案 0 :(得分:1)
你不能在Swift中将任意字节粘贴到字符串文字中。您需要将其存储为UInt8
或Data
的数组。例如:
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
答案 1 :(得分:1)
您的编码字符串由序列16位Unicode值(\X2\
和\X0
分隔符之间的十六进制数字)组成。当你从中提取值时,你会得到这个:
let bytes = [ 0x041F, 0x0435, 0x0440, 0x0435, 0x043A, 0x0440, 0x044B, 0x0442, 0x0438, 0x0435 ]
您可以使用此转换为String:
var s = ""
s.unicodeScalars.append(contentsOf: bytes.flatMap { UnicodeScalar($0) } )
print(s) // prints "Перекрытие"