jdl
jdl

Reputation: 6323

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' 

Upvotes: 0

Views: 85

Answers (2)

Ken Thomases
Ken Thomases

Reputation: 90611

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];

Upvotes: 1

CRD
CRD

Reputation: 53010

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

Upvotes: 2

Related Questions