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

Chi*_*ong 45 iphone bytearray objective-c type-conversion

我想转换NSData为字节数组,所以我写下面的代码:

NSData *data = [NSData dataWithContentsOfFile:filePath];
int len = [data length];
Byte byteData[len];
byteData = [data bytes];
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*her 60

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

尝试:

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

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

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


ste*_*vex 42

您也可以只使用它们所在的字节,将它们转换为您需要的类型.

unsigned char *bytePtr = (unsigned char *)[data bytes];
Run Code Online (Sandbox Code Playgroud)


Khu*_*Sim 13

已经回答,但要概括以帮助其他读者:

    //Here:   NSData * fileData;
    uint8_t * bytePtr = (uint8_t  * )[fileData bytes];

    // Here, For getting individual bytes from fileData, uint8_t is used.
    // You may choose any other data type per your need, eg. uint16, int32, char, uchar, ... .
    // 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 ?

    // Now, if you want to access whole data (fileData) as an array of uint8_t
    NSInteger totalData = [fileData length] / sizeof(uint8_t);

    for (int i = 0 ; i < totalData; i ++)
    {
        NSLog(@"data byte chunk : %x", bytePtr[i]);
    }
Run Code Online (Sandbox Code Playgroud)


Nic*_*ley 9

签名-[NSData bytes]- (const void *)bytes.您无法为堆栈上的数组指定指针.如果要将NSData对象管理的缓冲区复制到数组中,请使用-[NSData getBytes:].如果你想在不复制的情况下这样做,那就不要分配一个数组; 只需声明一个指针变量,然后NSData为你管理内存.