0

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.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • If you want more concrete help, you'll have to be more specific about what problem you're trying to solve by passing NSData to an API that wants a `const char*`. – merlin2011 Jul 11 '18 at 23:00
  • alright, basically I need the API to set a hex stream for me. So maybe the question is how to convert NSData to const char * that encodes a hex stream? Is that more clear? – Mongo Hooli Jul 11 '18 at 23:43
  • Are you putting it into a hex stream to read it out again later (reconstruct the object), or to print to the screen? The other end matters for this question. – merlin2011 Jul 12 '18 at 00:13
  • To reconstruct the object I would say – Mongo Hooli Jul 12 '18 at 00:28
  • See the update to my answer. – merlin2011 Jul 12 '18 at 00:36

2 Answers2

0

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.

merlin2011
  • 71,677
  • 44
  • 195
  • 329
0

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.

Update

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];
Asleepace
  • 3,466
  • 2
  • 23
  • 36