views:

149

answers:

1

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?

+1  A: 

Is there any reason you are storing the values as longs? For Unicode storage you only need to store the values as UInt32, which would then make it easy to interpret the data as UTF-32 by doing something like this:

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: 杞⌘☺
Rob Keniger