简体   繁体   English

Objective-C int转换为UTF-8

[英]Objective-C int convert to UTF-8

I want to convert this int num: 53392 to cyrillic letter A . 我想将此int num: 53392转换为西里尔字母A I use this: NSString *string = [NSString stringWithFormat:@"%c", 53392]; 我用这个: NSString *string = [NSString stringWithFormat:@"%c", 53392]; But this now work properly and return me strange symbols. 但这现在可以正常工作,并向我返回奇怪的符号。 Can someone help me? 有人能帮我吗?

First, use %C format (capital letter C). 首先,使用%C格式(大写字母C)。 Second, code for cyrillic A is 0x0410, not your number. 其次,西里尔字母A的代码是0x0410,而不是您的电话号码。

创建包含Unicode字符的NSString的正确方法是使用stringWithUTF8String和\\ u ####转义序列,如下所示:

NSString *aString = [NSString stringWithUTF8String:"To be continued\u2026"];

The integer you have, 53392, is the two bytes 0xD0 and 0x90 packed into an integer, which are the UTF-8 encoding of the Unicode 0x410 (decimal 1040) cyrillic capital A. 您拥有的整数53392是打包为整数的两个字节0xD0和0x90,它们是Unicode 0x410(十进制1040)西里尔字母A的UTF-8编码。

There are multiple ways to do your conversion, here are two. 进行转换的方法有多种,这里有两种。

If you know the UTF-8 sequence (which you can extract out of the integer if needed) you can convert it to an NSString using a sequence like: 如果您知道UTF-8序列(可以根据需要从整数中提取出来),则可以使用以下序列将其转换为NSString

char buf[2];
buf[0] = 0xD0;
buf[1] = 0x90;
NSString *cyrillicA = [[NSString alloc] initWithBytes:buf length:2 encoding:NSUTF8StringEncoding];

If you know the UTF-16 value you can use the %C format: 如果您知道UTF-16值,则可以使用%C格式:

NSString *cyrillicA = [NSString stringWithFormat:@"%C", 0x410];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM