Retrieve NSData to Hex by length

与世无争的帅哥 提交于 2019-12-11 09:49:23

问题


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


来源:https://stackoverflow.com/questions/7805340/retrieve-nsdata-to-hex-by-length

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!