UInt8 XOR'd array result to NSString conversion returns nil every time

久未见 提交于 2019-12-13 05:25:38

问题


I'm having issues working with iOS Swift 2.0 to perform an XOR on a [UInt8] and convert the XORd result to a String. I'm having to interface with a crude server that wants to do simple XOR encryption with a predefined array of UInt8 values and return that result as a String.

Using iOS Swift 2.0 Playground, create the following array:

let xorResult : [UInt8] = [24, 48, 160, 212]   // XORd result
let result = NSString(bytes: xorResult, length: xorResult.count, encoding: NSUTF8StringEncoding)

The result is always nil. If you remove the 160 and 212 values from the array, NSString is not nil. If I switch to NSUTF16StringEncoding then I do not receive nil, however, the server does not support UTF16. I have tried converting the values to a hex string, then converting the hex string to NSData, then try to convert that to NSUTF8StringEncoding but still nil until I remove the 160 and 212. I know this algorithm works in Java, however in Java we're using a combination of char and StringBuilder and everything is happy. Is there a way around this in iOS Swift?


回答1:


To store an arbitrary chunk of binary data as as a string, you need a string encoding which maps each single byte (0 ... 255) to some character. UTF-8 does not have this property, as for example 160 is the start of a multi-byte UTF-8 sequence and not valid on its own.

The simplest encoding with this property is the ISO Latin 1 aka ISO 8859-1, which is the ISO/IEC 8859-1 encoding when supplemented with the C0 and C1 control codes. It maps the Unicode code points U+0000 .. U+00FF to the bytes 0x00 .. 0xFF (compare 8859-1.TXT).

This encoding is available for (NS)String as NSISOLatin1StringEncoding.

Please note: The result of converting an arbitrary binary chunk to a (NS)String with NSISOLatin1StringEncoding will contain embedded NUL and control characters. Some functions behave unexpectedly when used with such a string. For example, NSLog() terminates the output at the first embedded NUL character. This conversion is meant to solve OP's concrete problem (creating a QR-code which is recognized by a 3rd party application). It is not meant as a universal mechanism to convert arbitrary data to a string which may be printed or presented in any way to the user.



来源:https://stackoverflow.com/questions/34496343/uint8-xord-array-result-to-nsstring-conversion-returns-nil-every-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!