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>?
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: .
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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.