Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSString to unsigned char * for iphone application

I am trying to convert NSString in to unsigned char* for iphone application . and i am newly for this objective C and iphone application so please help on this . Whether is there any api is there which can help for converting NSString to unsigned char*.

Thanks, KamalBhr

like image 686
KamalBhr Avatar asked Nov 26 '09 11:11

KamalBhr


2 Answers

Well, the question is a bit of a mis-nomer, because typing isn't the only thing you have to worry about. Not only do you need to worry about access, but you also need to worry about encoding. Assuming you just want the UTF8 encoding, than you can get away with:

NSString *myString = @"Hello";
const unsigned char *string = (const unsigned char *) [myString UTF8String];

If, however, you need access to one-byte per character data, than you probably want one of the other encodings, like ASCII:

NSString *myString = @"Hello";
const unsigned char *string = (const unsigned char *) [myString cStringUsingEncoding:NSASCIIStringEncoding];

The other valuable encoding that you might want to use is Latin1, which gets you standard ASCII, along with accented characters and symbols used by most languages in Western Europe and the U.S.: NSISOLatin1StringEncoding

like image 137
Douglas Mayle Avatar answered Sep 21 '22 06:09

Douglas Mayle


NSString reference is your help. NSString has these functions to convert it to c-string:

- (const char *)UTF8String;
- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
- (BOOL)getCString:(char *)buffer maxLength:(NSUInteger)maxBufferCount encoding:(NSStringEncoding)encoding

And there's also a similar question.

like image 23
Vladimir Avatar answered Sep 24 '22 06:09

Vladimir