1

I have a objc function like below

-(char *)decrypt:(char *)crypt el:(int)el{}

when I call this function from swift it returns UnsafeMutablePointer<Int8>. Now I need to get the data from this pointer. The output should be a string like this

"5c9f2cb88787fff26ca8a57982604460201805111017510011111111"

I have tried below code to retrieve the value

String(validatingUTF8: pointer)

But it returns nil. How do I get the value from this UnsafeMutablePointer<Int8>?

udi
  • 303
  • 1
  • 6
  • 19
  • check this https://stackoverflow.com/questions/33974704/ios-convert-unsafemutablepointerint8-to-string-in-swift – Abdelahad Darwish May 11 '18 at 07:28
  • What format is the data pointed to by the `char *` in? Is it UTF-8 or is it raw binary data (since your example string only uses characters that could be hex digits)? Is it null terminated? – Charles Srstka May 11 '18 at 07:28
  • Best guess is that the data is no a valid UTF-8 string. Look at the hex representation and verify it is valid or use `String(validatingUTF8: pointer)` where non UTF-8 values will be displayed as the unicode error symbol: �. If there decryption failed the result is more than likely invalid UTF-8. – zaph May 11 '18 at 07:33
  • 1
    Possibly helpful: [How to convert Data to hex string in swift](https://stackoverflow.com/questions/39075043/how-to-convert-data-to-hex-string-in-swift) – Martin R May 11 '18 at 07:49

2 Answers2

0

Best guess is that the data is no a valid UTF-8 string.

If there decryption failed the result is more than likely invalid UTF-8 but this is just a diagnostic.

Look at the hex representation and verify it is valid or use String(validatingUTF8: pointer) where non UTF-8 values will be displayed as the unicode error symbol: �.

zaph
  • 111,848
  • 21
  • 189
  • 228
0

I'm going to go out on a limb here and assume that your char * doesn't actually point to UTF-8 data, but rather to raw binary data of which you are hoping to get a hexadecimal representation. You can do that via:

// You'll need to know the length of the data. If it's null-terminated,
// read through the pointer until you hit a zero byte; otherwise, use whatever
// facility the API you're using provides to get the data length.
let buffer = UnsafeBufferPointer(start: $0, count: __insert_length_here__)

// and so:
let hexString = buffer.reduce(into: "") { $0 += String(format: "%02x", $1) }

print(hexString) // ta da!
Charles Srstka
  • 16,665
  • 3
  • 34
  • 60