如何在iPhone中将NSData转换为字节数组?

我想转换NSData为字节数组,因此编写以下代码:


NSData *data = [NSData dataWithContentsOfFile:filePath];

int len = [data length];

Byte byteData[len];

byteData = [data bytes];

但是最后一行代码弹出一个错误,提示“分配中的类型不兼容”。那么将数据转换为字节数组的正确方法是什么?


RISEBY
浏览 496回答 3
3回答

MM们

您不能使用变量声明数组,因此Byte byteData[len];将无法使用。如果要从指针复制数据,则还需要memcpy(它将遍历指针指向的数据并将每个字节复制到指定的长度)。尝试:NSData *data = [NSData dataWithContentsOfFile:filePath];NSUInteger len = [data length];Byte *byteData = (Byte*)malloc(len);memcpy(byteData, [data bytes], len);这段代码将动态地将数组分配给正确的大小(free(byteData)完成后必须提供),并将字节复制到其中。getBytes:length:如果要使用固定长度的数组,也可以按照其他人的指示使用。这样可以避免malloc / free,但是扩展性较差,更容易出现缓冲区溢出问题,因此我很少使用它。

森林海

您也可以只使用它们所在的字节,将其转换为所需的类型。unsigned char *bytePtr = (unsigned char *)[data bytes];

qq_花开花谢_0

已经回答,但可以概括一下以帮助其他读者:&nbsp; &nbsp; //Here:&nbsp; &nbsp;NSData * fileData;&nbsp; &nbsp; uint8_t * bytePtr = (uint8_t&nbsp; * )[fileData bytes];&nbsp; &nbsp; // Here, For getting individual bytes from fileData, uint8_t is used.&nbsp; &nbsp; // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .&nbsp; &nbsp; // Make sure, fileData has atleast number of bytes that a single byte chunk would need. eg. for int32, fileData length must be > 4 bytes. Makes sense ?&nbsp; &nbsp; // Now, if you want to access whole data (fileData) as an array of uint8_t&nbsp; &nbsp; NSInteger totalData = [fileData length] / sizeof(uint8_t);&nbsp; &nbsp; for (int i = 0 ; i < totalData; i ++)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; NSLog(@"data byte chunk : %x", bytePtr[i]);&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

iOS