Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert wchar_t to NSString?

I have wchar_t buffer [100] . Sometimes it needed for Unicode letters, sometimes is not.

I need to convert it to NSString.

I'm using NSString *str = [NSString string:(char *)buffer]; to conver it.

When I'm trying to NSLog my NSString, sometimes it getting right result, but sometimes is not.

Did I miss something?

Thanks!

like image 315
User1234 Avatar asked Oct 13 '11 11:10

User1234


2 Answers

Everything is as Totumus Maximus has said, but additionally you need to know how the characters in your buffer are encoded. As wchar_t is 32 bits you probably have some 32 bit encoding of which UTF32-LE is the most likely. What you want to do to get your NSString is:

NSString* result = [[NSString alloc] initWithBytes: (const void*)buffer 
                                            length: sizeof(wchar_t) * numberOfCharsInBuffer
                                          encoding: someEncoding];

where:

  • numberOfCharsInBuffer is the number of wchar_ts in the buffer that you want to decode. The method above does not assume that the string is null terminated and will happily try to put nulls into the NSString if they appear before the length you specify (note that with wchar_t "null" means a 32 bit value that is zero).
  • someEncoding is the encoding used by the string in the buffer. Try NSUTF32StringEncoding, NSUTF32LittleEndianStringEncoding, NSUTF32BigEndianStringEncoding.
like image 184
JeremyP Avatar answered Sep 28 '22 00:09

JeremyP


My converter for "char", "wchar_t", "NSString". Use and enjoy.

//-=(W)=-

+(NSString *)stringFromChar:(const char *)charText
{
    return [NSString stringWithUTF8String:charText];
}

+(const char *)charFromString:(NSString *)string
{
    return [string cStringUsingEncoding:NSUTF8StringEncoding];
}

+(NSString *)stringFromWchar:(const wchar_t *)charText
{
    //used ARC
    return [[NSString alloc] initWithBytes:charText length:wcslen(charText)*sizeof(*charText) encoding:NSUTF32LittleEndianStringEncoding];
}

+(const char /*wchar_t*/ *)wcharFromString:(NSString *)string
{
    return  [string cStringUsingEncoding:NSUTF8StringEncoding];
}
like image 22
user1351086 Avatar answered Sep 28 '22 01:09

user1351086