I am trying to convert a NSData object with audio data to a const char *. I have to do this because the API I am trying to call expects const char *. But I am unable to do so as
const char * stream = [data bytes]; //won't compile
also
const char * stream = (const char *)[data bytes];
will compile but will only have the first 2 bytes for some reason.
Thanks in advance.
const char*
is assumed to point at a null-terminated string, so the first null character in the NSData
object will terminate the string.
Performing this conversion using a cast does not make sense out of context, since it's just asking the API to interpret an NSData as a const char*
.
If you are trying to pass an NSData to an API that wants const char*
, you are likely to be using the wrong API for your purpose, or you need to re-encode your data before using the API.
Update: Based on the OP's comment, he wants to encode the data to decode it later.
There are a variety of different solutions for this, but one simple possibility is to base64
encode the data using the API method . You could then base64
decode it using the symmmetric API method . You could then convert the resulting NSString
to const char*
using the approach suggested in this answer .
Assuming the NSData you are loading is originally a string, you can try something like this:
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
const char *chars = [string UTF8String];
This will first convert the NSData to a NSString, and then convert the NSString to const char pointer.
Since you are trying to just encode the data as a hex string, take a look at this thread:
How to convert an NSData into an NSString Hex string?
It should look something like this:
NSUInteger capacity = data.length * 2;
NSMutableString *sbuf = [NSMutableString stringWithCapacity:capacity];
const unsigned char *buf = data.bytes;
NSInteger i;
for (i=0; i<data.length; ++i)
{
[sbuf appendFormat:@"%02X", (NSUInteger)buf[i]];
}
const char *chars = [sbuf UTF8String];
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.