简体   繁体   中英

NSData to NSMutableArray of NSData by fixed length

I am trying to get NSMutableArray from NSData by 16 bytes, but failing to do so. Maybe anyone could point me in the right direction.

Example: input: <c4ebc39d edf81fe6 09e0a41a 34b4d20d c4ebc39d edf81fe6 09e0a41a 34b4d20d>

output: <c4ebc39d edf81fe6 09e0a41a 34b4d20d> <c4ebc39d edf81fe6 09e0a41a 34b4d20d>

I am trying like this:

NSMutableArray *blocks = [[NSMutableArray alloc]init];
for (NSUInteger i = 0; i <= [data length]; i=i+16) {
    unsigned char *byte = NULL;
    [data getBytes:byte range:NSMakeRange(i, 16)];
    NSData *temp = [[NSData alloc] initWithBytes:byte length:sizeof(byte)];
    [blocks addObject:temp];
}

For some reason this throws me exc_bad_access.

[data getBytes:byte range:NSMakeRange(i, 16)];

copies the data into the memory pointed to by byte , it does not allocate memory. Copying the data crashes because byte == NULL does not point to valid memory. Replacing

unsigned char *byte = NULL;

by

unsigned char byte[16];

should solve the problem. But note that

NSData *temp = [data subdataWithRange:NSMakeRange(i, 16)];

is even easier and does not require the byte buffer at all.

Note also that the for loop

for (NSUInteger i = 0; i <= [data length]; i=i+16)

should be changed to

for (NSUInteger i = 0; i <= [data length] - 16; i=i+16)

to avoid access to the data object beyond its bounds.

You loop would then look like this:

for (NSUInteger i = 0; i <= [data length] - 16; i = i + 16) {
    NSData *temp = [data subdataWithRange:NSMakeRange(i, 16)];
    [blocks addObject:temp];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM