如何转换wchar_t NSString? [英] How to convert wchar_t to NSString?

查看:320
本文介绍了如何转换wchar_t NSString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有wchar_t缓冲区[100]。有时它需要Unicode字符,有时不需要。

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

我需要将其转换为NSString。

I need to convert it to NSString.

'm using NSString * str = [NSString string:(char *)buffer]; 来收敛。

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

当我尝试NSLog我的NSString,有时它得到正确的结果,但有时不是。

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

我错过了什么?

谢谢!

推荐答案

正如Totumus Maximus所说,但另外你需要知道你的缓冲区中的字符是如何编码的。因为 wchar_t 是32位,你可能有一些32位编码,其中UTF32-LE是最可能的。你想要做什么来获得你的NSString是:

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];

其中:


  • numberOfCharsInBuffer 是您要解码的缓冲区中的 wchar_t 的数目。上面的方法不假定字符串是null终止,并且乐意尝试将nulls放入NSString如果它们出现在你指定的长度之前(注意,使用wchar_tnull意味着一个32位的值为零)。

  • someEncoding 编码。尝试 NSUTF32StringEncoding `NSUTF32LittleEndianStringEncoding NSUTF32BigEndianStringEncoding 。 >
  • 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.

这篇关于如何转换wchar_t NSString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆