iOS Padawan
iOS Padawan

Reputation: 418

How to convert an "initWithBytes" NSString to unsigned char*

How to convert an "initWithBytes" NSString to unsigned char*?

here's how the NSString produced

NSString *byte = [[[NSString alloc] initWithBytes:inputbytes length:inputlength encoding:NSASCIIStringEncoding] autorelease];

which contains bytes data that should not be changed in bit level(will be the input of base64 conversion)

The data in the byte is 0x01 0x00 0x01, 3 bytes

and I want to convert it into an unsigned char*

How should I do it?

Thanks

Upvotes: 0

Views: 1698

Answers (2)

Jonathan Grynspan
Jonathan Grynspan

Reputation: 43472

Generally speaking, you should work with NSString directly rather than attempting to move in and out of Objective-C. But there are reasons to drop down to C (e.g. using a C-only API) so I'll humour you. ;)

If you just need to pass the data to another function, you can do this:

const unsigned char *cString = (const unsigned char *)[byte cStringUsingEncoding: NSASCIIStringEncoding];

If you need to modify the C string (i.e. make it non-const), you will need to make a copy:

const unsigned char *cString = (const unsigned char *)strdup([byte cStringUsingEncoding: NSASCIIStringEncoding]);

And then free() it when you're done with it:

free(cString);

Note that this will not modify the original C string or the NSString you made from it. If you need an NSString you can modify, use NSMutableString.

Upvotes: 2

Related Questions