ObjC / iOS:如何检索字符的unicode十六进制代码?

时间:2014-01-29 16:31:29

标签: objective-c unicode nsstring

所以,我知道如何将unicode十六进制代码转换为由该代码引用的unicode字符组成的NSString:

NSString *ucStr = @"\\u004A"; // hex code for capital J
NSString *theLetter = [ucStr mutableCopy];
CFStringRef transform = CFSTR("Any-Hex/Java");
CFStringTransform((__bridge CFMutableStringRef)theLetter, NULL, transform, YES);
// theLetter is now @"J"

...但是,我似乎不明白如何向另一个方向前进,即从NSString @"J"开始,输出NSString @"004A"

1 个答案:

答案 0 :(得分:0)

只需提取每个字符并使用格式字符串@"%04x"对其进行格式化,如下所示:

NSString *input = @"How now brown cow";
for (NSUInteger i = 0; i < [input length]; i++) {
    unichar c = [input characterAtIndex:i];
    NSLog(@"%04x", (unsigned)c);
    // or NSString *s = [NSString stringWithFormat:@"%04x", (unsigned)c];
}

BTW我不明白你发布的代码,但因为这不是问题,所以没关系。