0

I'm storing large unicode characters (0x10000+) as long types which eventually need to be converted to NSStrings. Smaller unicode characters can be created as a unichar, and an NSString can be created using

[NSString stringWithCharacters:(const unichar *)characters length:(NSUInteger)length]

So, I imagine the best way to get an NSString from the unicode long value would be to first get a unichar* from the long value. Any idea on how I might go about doing this?

4

1 回答 1

1

有什么理由将值存储为longs?对于 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: 杞⌘☺
于 2010-04-21T02:01:37.253 回答