如何将“a”编码为“6100”?

时间:2013-10-21 15:52:01

标签: iphone objective-c encoding nsstring

我需要将字符串编码为其他格式。任何人都知道这是什么类型的编码? 如何使用objective-c获得结果?

更新2013-10-22 02:23:49

我不确定这是不是最好的方法。它解决了我的问题。

NSString *result_string = @"";
for (int i = 0; i < string.length; i++) {
    int a = [string characterAtIndex:i];
    unsigned long long int theNumber = a;
    NSString *ascii_string = [NSString stringWithFormat:@"%llX", theNumber];

    //61 -> 6100, 4E03 -> 034E
    if (ascii_string.length == 2) {
        result_string = [NSString stringWithFormat:@"%@%@00", result_string, ascii_string];

    } else if (ascii_string.length == 4) {
        NSString *first2 = [ascii_string substringToIndex:2];
        NSString *last2 = [ascii_string substringFromIndex:2];
        result_string = [NSString stringWithFormat:@"%@%@%@", result_string, last2, first2];

    } else {
        NSLog(@"length unknown: %d", ascii_string.length);
    }

}

return result_string;

1 个答案:

答案 0 :(得分:2)

我将采取一个平底船,并猜测你通过查看一些数据流得到6100,并且它是用小端编码的UTF-16编码。

所以这样的事情会起作用:

NSString *str = @"the quick brown fox jumps over the lazy dog";
NSData *data = [str dataUsingEncoding:NSUTF16LittleEndianStringEncoding];
// data can now be written to file or transmitted over the network.