0

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.

1 Answers1

1

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);
pmdj
  • 22,018
  • 3
  • 52
  • 103
  • Or `cStringUsingEncoding:` – Cy-4AH Oct 21 '19 at 13:13
  • 1
    @Cy-4AH [The documentation for `cStringUsingEncoding:`](https://developer.apple.com/documentation/foundation/nsstring/1408489-cstringusingencoding?language=objc) states "**Special Considerations** UTF-16 and UTF-32 are not considered to be C string encodings, and should not be used with this method—the results of passing NSUTF16StringEncoding, NSUTF32StringEncoding, or any of their variants are undefined." So no, don't use `cStringUsingEncoding:` here. – pmdj Oct 21 '19 at 13:14
  • i mean okay `static const UniCharT s_learnWord[] = {'H', 'e','l','\0'};` if i pass this it is working fine, can you please suggest me how to convert like `s_learnWord` from `NSString` – Praveen Kumar Oct 21 '19 at 13:16
  • @PraveenKumar I've given an example that should help you get started. – pmdj Oct 21 '19 at 13:22
  • @pmdj Thanks man you are right i need to convert `UTF16String`, working fine now – Praveen Kumar Oct 22 '19 at 06:37