2017-05-30 83 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)