byteArray到Hex NSString - 添加了一些错误的十六进制内容

时间:2016-01-30 04:30:48

标签: ios objective-c nsstring hex

我正在尝试将byteArray转换为Hex NSString。

这是我提到的解决方案,将其转换为十六进制NSString。但是,我发现它添加了 ffffffffffffff 。我怎样才能获得正确的十六进制NSString?

Best way to serialize an NSData into a hexadeximal string

const char myByteArray[] = {
        0x12,0x23,0x34,0x45,0x56,0x67,0x78,0x89,
        0x12,0x23,0x34,0x45,
        0x56,0x67,0x78,0x89 };

    NSData *myByteData=[NSData dataWithBytes:myByteArray length:sizeof(myByteArray)];
    NSMutableString *myHexString= [NSMutableString stringWithCapacity:myByteData.length*2];
    for(int i=0;i<myByteData.length;i++){
        ;
        NSString *resultString =[NSString stringWithFormat:@"%02lx",(unsigned long)myByteArray[i]];
        [myHexString appendString:resultString];
    }

输出字符串

12233445566778ffffffffffffff8912233445566778ffffffffffffff89

2 个答案:

答案 0 :(得分:1)

不要为每个字节使用unsigned long。如果您不使用它,myByteData的重点是什么?

由于您实际上并未使用char,请使用uint8_t

试试这个:

const uint8_t myByteArray[] = {
    0x12,0x23,0x34,0x45,0x56,0x67,0x78,0x89,
    0x12,0x23,0x34,0x45,
    0x56,0x67,0x78,0x89 };

size_t len = sizeof(myByteArray) / sizeof(uint8_t);
NSMutableString *myHexString = [NSMutableString stringWithCapacity:len * 2];
for (size_t i = 0; i < len; i++) {
    [myHexString appendFormat:@"%02x", (int)myByteArray[i]];
}

答案 1 :(得分:0)

您的初始字节数据为char而不是unsigned char。这意味着任何值> 127(0x7f)将被视为二进制补码负数,给出ffffffffffffff89

如果您将数据更改为unsigned char,您将获得所需的结果。

const unsigned char myByteArray[] = {
        0x12,0x23,0x34,0x45,0x56,0x67,0x78,0x89,
        0x12,0x23,0x34,0x45,
        0x56,0x67,0x78,0x89 };

NSData *myByteData=[NSData dataWithBytes:myByteArray length:sizeof(myByteArray)];
NSMutableString *myHexString= [NSMutableString stringWithCapacity:myByteData.length*2];
for(int i=0;i<myByteData.length;i++){

    NSString *resultString =[NSString stringWithFormat:@"%02lx",(unsigned long)myByteArray[i]];
    [myHexString appendString:resultString];

}