2017-05-30 27 views
0

我需要将常规字符串(字符串或NSString)编码为Code Page 850 format将字符串/ NSString编码到代码页850格式

有一个支持这种格式的外部字符串enconding(在CFStringEncoding enum中称为dosLatin1)。我不知道它是否真的可以完成这项工作,但它是我在整个iOS文档中发现的代码页850的唯一参考。

如何使用CFStringEnconding将“常规”字符串转换为CP850格式的字符串?这是做这件事的最好方法吗?

回答

1

如果你可以通过CP 1252这是“现代”850替代品,那么你可以使用Swift String的内置转换。否则,您可以尝试使用Core Foundation的转换方法。

let swiftString = "This is a string" 

// Easy way -- use Swift String plus "modern" CP 1252 eoncding to get a block of data. Note: does not include BOM 
if let data = swiftString.data(using: .windowsCP1252, allowLossyConversion: true) { 
    print(data) // Do something with the resulting data 
} 

// The more thorough way to use CP 850 (enum value = 1040) -- use Core Foundation. This will produce a BOM if necessary. 
let coreFoundationString = swiftString as CFString 
let count = CFStringGetLength(coreFoundationString) * 2 
var buffer = [UInt8](repeating: 0, count: count) 
let resultCount = CFStringGetBytes(coreFoundationString as CFString, CFRangeMake(0, CFStringGetLength(coreFoundationString)), 1040, 0x41, true, &buffer, count, nil) 
print(buffer)