How to convert NSData to byte array in iPhone?

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?


Solution 1:

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).

Try:

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

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.

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.

Solution 2:

You could also just use the bytes where they are, casting them to the type you need.

unsigned char *bytePtr = (unsigned char *)[data bytes];