Search code examples
objective-cstringnsdatac-strings

Converting NSData that contains UTF-8 and null bytes to string


I have an __NSCFData object. I know what's inside it.

61 70 70 6c 65 2c 74 79 70 68 6f 6f 6e 00 41 52 4d 2c 76 38 00

I tried converting it to a string with initWithData: and stringWithUTF8String: and it gives me "apple,typhoon". The conversion is terminated at 00

The data actually is

61 a
70 p
70 p
6c l
65 e
2c ,
74 t
79 y
70 p
68 h
6f o
6f o
6e n
00 (null)
41 A
52 R
4d M
2c ,
76 v
38 8
00 (null)

How can I properly convert this without loss of information?


Solution

  • The documentation for stringWithUTF8String describes its first parameter as:

    A NULL-terminated C array of bytes in UTF8 encoding.

    Which is why your conversion stops at the first null byte.

    What you appear to have is a collection of C strings packed into a single NSData. You can convert each one individually. Use the NSData methods bytes and length to obtain a pointer to the bytes/first C string and the total number of bytes respectively. The standard C function strlen() will give you the length in bytes of an individual string. Combine these and some simple pointer arithmetic and you can write a loop which converts each string and, for example, stores them all into an array or concatenates them.

    If you get stuck implementing the solution ask a new question, show your code, and explain the issue. Someone will undoubtedly help you with the next step.

    HTH