如何将 unicode 十六进制数字变量转换为 NSString 中的字符? [英] How to convert unicode hex number variable to character in NSString?

查看:78
本文介绍了如何将 unicode 十六进制数字变量转换为 NSString 中的字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有一系列 unicode 数字,我想在 UILabel 中显示它们,如果我对它们进行硬编码,我可以显示它们,但这太慢了,所以我想用一个变量替换它们,然后更改变量和获取相关字符.例如,现在我知道 unicode 是 U+095F,我想在 UILabel 中显示 U+095F 到 U+096f 的范围,我可以用像

Now I have a range of unicode numbers, I want to show them in UILabel, I can show them if i hardcode them, but that's too slow, so I want to substitute them with a variable, and then change the variable and get the relevant character. For example, now I know the unicode is U+095F, I want to show the range of U+095F to U+096f in UILabel, I can do that with hardcode like

NSString *str = [NSString stringWithFormat:@"\u095f"];

NSString *str = [NSString stringWithFormat:@"\u095f"];

但我想这样做

NSInteger 十六进制 = 0x095f;

NSInteger hex = 0x095f;

[NSString stringWithFormat:@"\u%ld", (long)hex];

[NSString stringWithFormat:@"\u%ld", (long)hex];

我可以自动更改十六进制,就像使用 @"%ld", (long)hex 一样,所以有人知道如何实现吗?

I can change the hex automatically,just like using @"%ld", (long)hex, so anybody know how to implement that?

推荐答案

您可以使用十六进制字节的缓冲区来初始化字符串(您只需提供其指针).关键是,要注意的重要一点是您提供了要应用的字符编码.具体来说,您应该注意字节顺序.

You can initialize the string with the a buffer of bytes of the hex (you simply provide its pointer). The point is, and the important thing to notice is that you provide the character encoding to be applied. Specifically you should notice the byte order.

这是一个例子:

UInt32 hex = 0x095f;
NSString *unicodeString = [[NSString alloc] initWithBytes:&hex length:sizeof(hex) encoding:NSUTF32LittleEndianStringEncoding];

请注意,像使用 %C 格式这样的解决方案就可以了,只要您将它们用于 16 位 unicode 字符;32 位 unicode 字符,如表情符号(例如:0x1f601、0x1f41a)将无法使用简单格式.

Note that solutions like using the %C format are fine as long as you use them for 16-bit unicode characters; 32-bit unicode characters like emojis (for example: 0x1f601, 0x1f41a) will not work using simple formatting.

这篇关于如何将 unicode 十六进制数字变量转换为 NSString 中的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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