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!
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_t
s 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
.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];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With