将hexString转换为unicode字符串

时间:2015-05-28 18:43:07

标签: ios objective-c nsstring

我需要一个代码,将@“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];

请帮忙!

2 个答案:

答案 0 :(得分:0)

你走了:

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

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

答案 1 :(得分:0)

这对我有用

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位处理器上进行了测试