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
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
.
Try the cStringUsingEncoding: method of NSString:
https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html#//apple_ref/doc/uid/20000154-BAJHJHHD