如何在iPhone中将NSData转换为字节数组? [英] How to convert NSData to byte array in iPhone?

查看:137
本文介绍了如何在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?

推荐答案

你不能声明一个数组使用变量使字节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);

此代码将动态分配数组到正确的大小(您必须免费(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转换为字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆