我将大型unicode字符(0x10000
+)存储为long
类型,最终需要转换为NSStrings
。可以将较小的unicode字符创建为unichar
,并使用
NSString
[NSString stringWithCharacters:(const unichar *)characters length:(NSUInteger)length]
因此,我认为从unicode long值获取NSString
的最佳方法是首先从unichar*
值获取long
。关于我如何做到这一点的任何想法?
答案 0 :(得分:1)
是否有任何理由将值存储为long
s?对于Unicode存储,您只需将值存储为UInt32
,这样可以通过执行以下操作轻松将数据解释为UTF-32
:
int numberOfChars = 3;
UInt32* yourStringBuffer = malloc(sizeof(UInt32) * numberOfChars);
yourStringBuffer[0] = 0x2F8DB; //杞
yourStringBuffer[1] = 0x2318; //⌘
yourStringBuffer[2] = 0x263A; //☺
NSData* stringData = [NSData dataWithBytes:yourStringBuffer length:sizeof(UInt32) * numberOfChars];
//set the encoding according to the current byte order
NSStringEncoding encoding;
if(CFByteOrderGetCurrent() == CFByteOrderBigEndian)
encoding = NSUTF32BigEndianStringEncoding;
else
encoding = NSUTF32LittleEndianStringEncoding;
NSString* string = [[NSString alloc] initWithData:stringData encoding:encoding];
free(yourStringBuffer);
NSLog(@"%@",string);
//output: 杞⌘☺