How to convert unicode hex number variable to character in NSString?
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"];
but I want to do that like
NSInteger hex = 0x095f;
[NSString stringWithFormat:@"u%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.
Here's an example:
UInt32 hex = 0x095f;
NSString *unicodeString = [[NSString alloc] initWithBytes:&hex length:sizeof(hex) encoding:NSUTF32LittleEndianStringEncoding];
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.
喜欢这个:
unichar charCode = 0x095f;
NSString *s = [NSString stringWithFormat:@"%C",charCode];
NSLog(@"String = %@",s); //Output:String = य़
You would have to use
[NSString stringWithFormat:@"%C", (unichar)hex];
or directly declare the unichar (unsigned short)
as
unichar uni = 0x095f;
[NSString stringWithFormat:@"%C", uni];
A useful resource might be the String Format Specifiers, which lists %C
as
16-bit Unicode character (unichar), printed by NSLog() as an ASCII character, or, if not an ASCII character, in the octal format ddd or the Unicode hexadecimal format udddd, where d is a digit.
链接地址: http://www.djcxy.com/p/85240.html