omz:forum

    • Register
    • Login
    • Search
    • Recent
    • Popular

    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

    Pythonista
    2
    4
    2912
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • mikael
      mikael last edited by

      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?

      1 Reply Last reply Reply Quote 0
      • omz
        omz last edited by omz

        How about something like this:

        decoded_data = str(NSString.alloc().init(data=_data, encoding=NSUTF8StringEncoding))
        
        mikael 1 Reply Last reply Reply Quote 1
        • mikael
          mikael @omz last edited by

          @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.

          1 Reply Last reply Reply Quote 1
          • omz
            omz last edited by

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

            1 Reply Last reply Reply Quote 1
            • First post
              Last post
            Powered by NodeBB Forums | Contributors