7

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

bbum
  • 162,346
  • 23
  • 271
  • 359
KamalBhr
  • 133
  • 2
  • 4
  • 5

3 Answers3

20

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

idmean
  • 14,540
  • 9
  • 54
  • 83
Douglas Mayle
  • 21,063
  • 9
  • 42
  • 57
  • +1 for the `NSISOLatin1StringEncoding`. `NSASCIIStringEncoding` was failing because my string contained glyphs with an unsigned value > 128. – PassKit Aug 21 '14 at 10:11
4

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.

Community
  • 1
  • 1
Vladimir
  • 170,431
  • 36
  • 387
  • 313
0

You can try to use

- (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
Morion
  • 10,495
  • 1
  • 24
  • 33
  • 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 Nov 26 '09 at 11:49