toByteArray等价于目标c

时间:2016-12-19 16:47:03

标签: java ios objective-c

我目前正在同时处理一个Android和iOS项目,而且我正努力让数据编码得以解决。我在Java中有以下内容:

byte[] asByteArray = toByteArray("48656c6c6f576f72");
System.out.println("Byte Decode array" + Arrays.toString(asByteArray));

在控制台中,这为我提供了以下内容:

  

字节解码数组[72,101,108,108,111,87,111,114,108,100]

现在在目标c中,我并不完全确定如何获得NSData的等价物?

 NSData *plainData = [plainText dataUsingEncoding:NSUTF8StringEncoding];
 NSLog(@"Plain text decoded: %@",plainData);

我得到以下内容:

  

纯文本解码:< 32316564 35653765 31343664 63643335>

关于如何在Objective C中获得toByteArray函数的任何想法?

更新:将十六进制添加到基数10字符串表示

- (NSString *)hexResponseToDecimalNSData:(NSString *) response {
    NSMutableString *decimalResponse = [NSMutableString string];


    for(int i = 0; i < response.length; i+=2){
        NSString *substringResponse = [response substringWithRange:NSMakeRange((NSUInteger) i, 2)];

        unsigned result = 0;
        NSScanner *scanner = [NSScanner scannerWithString:substringResponse];
        [scanner scanHexInt:&result];
        [decimalResponse appendString:[NSString stringWithFormat:@"%d ",result]];
    }

    return decimalResponse
}

这个函数让我更接近像toByteArray函数Java.So如果我提供它

  

bbad42dfbf6e2680

它会返回

  

187 173 66 223 191 110 38 128

。我现在的问题是如何将187 173 66 223 191 110 38 128视为NSData?即作为一个8字节的NSData?

1 个答案:

答案 0 :(得分:1)

Java将字符串视为十六进制,每两个字符作为十六进制值并显示为带符号的十进制值。 ObjC dataUsingEncoding分别解释每个字符。

Objective-C不提供十六进制转换方法,因此需要编写一个。

以下是Apple使用的NSData实现的十六进制字符串:

NSData * dataFromHexString(NSString *hexString) {
    char buf[3];
    buf[2] = '\0';
    unsigned char *bytes = malloc([hexString length]/2);
    unsigned char *bp = bytes;
    for (CFIndex i = 0; i < [hexString length]; i += 2) {
        buf[0] = [hexString characterAtIndex:i];
        buf[1] = [hexString characterAtIndex:i+1];
        char *b2 = NULL;
        *bp++ = strtol(buf, &b2, 16);
    }

    return [NSData dataWithBytesNoCopy:bytes length:[hexString length]/2 freeWhenDone:YES];
}

示例:

NSString *hexString = @"21ed5e7e146dcd35";
NSLog(@"hexString: %@", hexString);
NSData *plainData = dataFromHexString(hexString);
NSLog(@"plainData: %@", plainData);

输出:     hexString:&#34; 21ed5e7e146dcd35&#34;
    plainData:&lt; 21ed5e7e146dcd35&gt;

注意,以下是相同的,只是一个不同的表示:

signed bytes:     33,  -19,   94,  126,   20,  109,  -51,   53
unsigned bytes:   33,  237,   94,  126,   20,  109,  205,   53
hex bytes:      0x21, 0xed, 0x5e, 0x7e, 0x14, 0x6d, 0xcd, 0x35