Lunayo
Lunayo

Reputation: 538

Retrieve NSData to Hex by length

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) ?

Upvotes: 1

Views: 2335

Answers (3)

neoneye
neoneye

Reputation: 52201

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];
}

Upvotes: 0

jbat100
jbat100

Reputation: 16827

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).

Upvotes: 0

omz
omz

Reputation: 53551

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.)

Upvotes: 4

Related Questions