本文介绍了如何在 iPhone 中将 NSData 转换为字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想把NSData转成字节数组,所以写了如下代码:

I want to convert NSData to a byte array, so I write the following code:

NSData *data = [NSData dataWithContentsOfFile:filePath];
int len = [data length];
Byte byteData[len];
byteData = [data bytes];

但是最后一行代码弹出一个错误,说赋值中的类型不兼容".那么将数据转换为字节数组的正确方法是什么?

But the last line of code pops up an error saying "incompatible types in assignment".What is the correct way to convert the data to byte array then?

推荐答案

您不能使用变量声明数组,因此 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.

这篇关于如何在 iPhone 中将 NSData 转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 05:44