简体   繁体   中英

How do I convert NSString to an encoding other than UTF-8?

I'm working with c in iOS Project I'm trying to convert my string to respected type in c, below code is supposed to send to core Library

typedef uint16_t    UniCharT;
static const UniCharT s_learnWord[] = {'H', 'e','l','\0'};

what i have done till now is string is the one what I'm passing

NSString * string = @"Hel";
static const UniCharT *a = (UniCharT *)[string UTF8String];

But it is failing to convert when more than one character, If i pass one character then working fine please let me where i miss, How can i pass like s_learnWord?

and i tried in google and StackOverFLow none of the duplicates or answers didn't worked for me like this Convert NSString into char array I'm already doing same way only.

Your question is a little ambiguous as the title says "c type char[]" but your code uses typedef uint16_t UniCharT; which is contradictory.

For any string conversions other than UTF-8, you normally want to use the method getCString:maxLength:encoding: .

As you are using uint16_t , you probably are trying to use UTF-16? You'll want to pass NSUTF16StringEncoding as the encoding constant in that case. (Or possibly NSUTF16BigEndianStringEncoding / NSUTF16LittleEndianStringEncoding )

Something like this should work:

include <stdlib.h>

// ...

NSString * string = @"part";
NSUInteger stringBytes = [string maximumLengthOfBytesUsingEncoding];
stringBytes += sizeof(UniCharT); // make space for \0 termination
UniCharT* convertedString = calloc(1, stringBytes);
[string getCString:(char*)convertedString
         maxLength:stringBytes
          encoding:NSUTF16StringEncoding];

// now use convertedString, pass it to library etc.

free(convertedString);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM