将 hexString 转换为 unicode 字符串

Convert hexString to unicode string

我需要一个代码,将@"043b" 转换为@"л"

这是我试过的

// get a hex string (@"0x043b")
NSString *hexString = [@"0x" stringByAppendingString:@"043b"];

// scan an unsined int from it (1083 as expected)
NSScanner* pScanner = [NSScanner scannerWithString:hexString];
unsigned int iValue;
[pScanner scanHexInt: &iValue];

// get a unichar from it (';')
NSNumber *number = [NSNumber numberWithUnsignedInt:iValue];
unichar character = [number unsignedCharValue];

// get a string (@";")
NSString *result = [NSString stringWithFormat:@"%C", character];

但我得到@";"而不是@"л"

我也试过了

// get a char (';')
char character = [number charValue];

// get a string (@";")
NSString * result = [NSString stringWithFormat:@"%c", character];

请帮忙!

给你:

unsigned long hexBytes = 0x3b04;
NSString *theString = [[NSString alloc] initWithBytes:&hexBytes length:sizeof(hexBytes) encoding:NSUnicodeStringEncoding];
NSLog(theString, @"");

要点:你必须反转你的字节,所以它是 0x3b04 而不是 0x043b。

这对我有用

int value = 0;
sscanf([@"043b" cStringUsingEncoding:NSUTF8StringEncoding], "%x", &value);

NSString *result = [NSString stringWithFormat:@"%C", value];

但是编译器在最后一行警告我,所以答案不是那么干净

Format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'

已在 32 位和 64 位处理器上测试