How to convert NSData to byte array in iPhone?
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.
You could also just use the bytes where they are, casting them to the type you need.
unsigned char *bytePtr = (unsigned char *)[data bytes];
Already answered, but to generalize to help other readers:
//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]); }