is it possible to convert NSString into unichar

3.6k views Asked by At

I have a NSString object and want to change it into unichar.

int decimal = [[temp substringFromIndex:2] intValue]; // decimal = 12298

NSString *hex = [NSString stringWithFormat:@"0x%x", decimal]; // hex = 0x300a

NSString *chineseChar = [NSString stringWithFormat:@"%C", hex];

// This statement log a different Chinese char every time I run this code 
NSLog(@"%@",chineseChar); 

When I see the log, It gives different character every time when I run my code. m I missing something...?

2

There are 2 answers

0
Adam Rosenfield On BEST ANSWER

The %C format specifier takes a 16-bit Unicode character (unichar) as input, not an NSString. You're passing in an NSString, which is getting reinterpreted as an integer character; since the string can be stored at a different address in memory each time you run, you get that address as an integer, which is why you get a different Chinese character every time you run your code.

Just pass in the character as an integer:

unichar decimal = 12298;
NSString *charStr = [NSString stringWithFormat:@"%C", decimal];
// charStr is now a string containing the single character U+300A,
// LEFT DOUBLE ANGLE BRACKET
0
Dave DeLong On

How about -[NSString characterAtIndex:]? It wants a character index and returns a unichar.