jdl February 2016

unicode assignment failing in NSString?

The following fails for both unichar assignments?

unsigned int c = 0x0001d122;
[NSString stringWithFormat:@"\U%@", [NSString stringWithFormat:@"%08X", c]];
[NSString stringWithFormat:@"\U%08X", c];

I am trying to do this programmatically (adding in the "\U" makes things difficult as seen above):

nssSymbol = @"\U0001d122"; \\this works... but need to be able to vary 'c' 

Answers


Ken Thomases February 2016

The handling of the \Unnnnnnnn construct in a string literal is done at compile time. You can't build the construct at run time and have it interpreted. That's not how things work.

You could do:

uint32_t c = 0x0001d122;
NSString* s = [[NSString alloc] initWithBytes:&c length:sizeof(c) encoding:NSUTF32LittleEndianStringEncoding];


CRD February 2016

As shown by Ken Thomases answer you can create a string from bytes, however you must know the endianness of your machine or use the endian conversion routines.

For example, on an Intel Mac which is little endian you can use:

uint32_t c = 0x0001d122;
NSString* s = [[NSString alloc] initWithBytes:&c
                                       length:sizeof(c)
                                     encoding:NSUTF32LittleEndianStringEncoding];

If you don't wish to code in knowledge of the systems endianness you can use the conversion routines. For example:

uint32_t c = EndianU32_NtoB(0x0001d122); // convert from native endianness to big endian
NSString* s = [[NSString alloc] initWithBytes:&c
                                       length:sizeof(c)
                                     encoding:NSUTF32BigEndianStringEncoding];

HTH

Post Status

Asked in February 2016
Viewed 2,890 times
Voted 13
Answered 2 times

Search




Leave an answer