遍历NSData的方法

来源:互联网 发布:淘宝5.6.0下载 编辑:程序博客网 时间:2024/06/05 07:58
    // 第一种方法    NSMutableString* resultAsHexBytes = [NSMutableString string];    NSString *string = @"abc";    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];    [data enumerateByteRangesUsingBlock:^(const void *bytes,                                          NSRange byteRange,                                          BOOL *stop) {        // To print raw byte values as hex        for (NSUInteger i = 0; i < byteRange.length; ++i) {            [resultAsHexBytes appendFormat:@"%02x", ((uint8_t*)bytes)[i]];        }        NSLog(@"resultAsHexBytes:%@", resultAsHexBytes);    }];    // 第二种方法    NSMutableString *result = [NSMutableString string];    const char *bytes = [data bytes];    for (int i = 0; i < [data length]; i++)    {        [result appendFormat:@"%02hhx", (unsigned char)bytes[i]];    }    NSLog(@"result:%@", result);

输出结果分别是:
result:616263
resultAsHexBytes:616263

值得注意的是,第一种方法只适用于iOS7之后的系统。

1 0
原创粉丝点击