Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
NSData to string
-
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?
-
How about something like this:
decoded_data = str(NSString.alloc().init(data=_data, encoding=NSUTF8StringEncoding))
-
@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.
-
@mikael Ah, that's much better actually. Forget my solution, I somehow forgot that function existed.