Forum Archive

NSData to string

mikael

Receiving NSData as _data, containing an encoded UTF-8 string as bytes, I ended up doing this to get back the original string:

decoded_data = bytearray(base64.b16decode(str(ObjCInstance(_data).CKUppercaseHexStringWithoutSpaces()))).decode()

I.e.:

  • Convert to hex string (uppercase for b16decode)
  • Convert to Python string
  • Decode back to bytes
  • Create a bytearray object
  • Finally decode as UTF-8 string

There must be a simpler way?

omz

How about something like this:

decoded_data = str(NSString.alloc().init(data=_data, encoding=NSUTF8StringEncoding))
mikael

@omz, thanks.

For completeness sake, I’ll include the option I found reading the manual, of all things:

decoded_data = objc_util.nsdata_to_bytes(ObjCInstance(_data)).decode()

Maybe more readable but less efficient than the direct ObjC UTF-decoding.

omz

@mikael Ah, that's much better actually. Forget my solution, I somehow forgot that function existed.