views:

874

answers:

3

Hello,

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

A: 

You can try to use

- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
Morion
Thank You for Quick response..i am trying this code....FileString = [[NSString alloc] initWithContentsOfFile:defaultPath];unsigned char * finalstring = [FileString UTF8Char]; but its not compiling..
KamalBhr
A: 

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.

Vladimir
thank you very much for your quick response and i got the solution..regards kamalBhr
KamalBhr
+3  A: 

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:NSASCIIStringEncodin];

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

Douglas Mayle