附加到const char *字节?

时间:2015-08-04 01:11:25

标签: objective-c char nsdata

我需要在第12个索引之后从NSData对象获取所有字节。

到目前为止我已经

const char* fileBytes = (const char*)[imageData bytes];
NSUInteger length = [imageData length];
NSUInteger index;


NSMutableString *byteString = [[NSMutableString alloc] init];

[SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"bytes: %@", imageData.description]];

for (index = 12; index<length; index++) { //Grabba returns a 12 byte header.
    char aByte = fileBytes[index];
    [byteString appendString:[NSString stringWithFormat:@"%x", aByte]];
}

但我真正想要做的是创建一个const char*并将每个字节追加到索引12直到结束。如何将字节附加到一系列字节?

1 个答案:

答案 0 :(得分:0)

您需要做的是使用一些标准的C库调用。您知道NSData对象中有多少字节,因此您可以分配所需的存储空间,然后记忆第12个字节中的所有字节。

NSUInteger length = [data length];
char* theBytes = malloc(sizeof(char)*(length-11));
memcpy(theBytes,fileBytes+11,length-11);

theBytes不能是const char *,因为在你调用memcpy之后它不会是常量。

记得在完成字符串后免费拨打电话。

相关问题