且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-04-17 14:49:29

您不能使用变量声明数组,因此 Byte byteData[len]; 将不起作用.如果要从指针复制数据,还需要memcpy(它会遍历指针指向的数据,将每个字节复制到指定长度).

You can't declare an array using a variable so Byte byteData[len]; won't work. If you want to copy the data from a pointer, you also need to memcpy (which will go through the data pointed to by the pointer and copy each byte up to a specified length).

试试:

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

此代码将动态分配数组到正确的大小(完成后必须free(byteData))并将字节复制到其中.

This code will dynamically allocate the array to the correct size (you must free(byteData) when you're done) and copy the bytes into it.

如果您想使用固定长度的数组,您也可以按照其他人的指示使用 getBytes:length:.这避免了 malloc/free,但可扩展性较差,更容易出现缓冲区溢出问题,因此我很少使用它.

You could also use getBytes:length: as indicated by others if you want to use a fixed length array. This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it.