Retrieve NSData to Hex by length

2019-07-29 14:57发布

问题:

I got a NSData that contain bytes like <00350029 0033> with length 6, is there any correct way to split the bytes to array somehow like (00, 35, 00, 29, 00, 33) ?

回答1:

NSData *data = ...;
NSMutableArray *bytes = [NSMutableArray array];
for (NSUInteger i = 0; i < [data length]; i++) {
    unsigned char byte;
    [data getBytes:&byte range:NSMakeRange(i, 1)];
    [bytes addObject:[NSString stringWithFormat:@"%x", byte]];
}
NSLog(@"%@", bytes);

(Assuming you want the bytes as a hex string representation, as in your example. Otherwise, use NSNumber.)



回答2:

You could use the NSData method

- (void)getBytes:(void *)buffer range:(NSRange)range

to get the bytes in a given range (after having allocated the right amount of memory, using malloc), then use

+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length

to create new small (1 byte long) data objects which you then put into an array. However if you just retrieve the pointer to the bytes themselves (using [data bytes]), that gives you a pointer (kind of an array in the C sense, not an NSArray, but could also be used and far more efficient).



回答3:

static NSString* HexStringFromNSData(NSData* data) {
    NSUInteger n = data.length;
    NSMutableString* s = [NSMutableString stringWithCapacity:(2 * n)];
    const unsigned char* ptr = [data bytes];
    for(NSUInteger i = 0; i < n; i++, ptr++) {
        [s appendFormat:@"%02x", (long)*ptr];
    }
    return [NSString stringWithString:s];
}