Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 588
Chilly Zhong Avatar asked Apr 07 '09 03:04

Chilly Zhong


People also ask

What is NSData in iOS?

A static byte buffer that bridges to Data ; use NSData when you need reference semantics or other Foundation-specific behavior. iOS 2.0+ iPadOS 2.0+ macOS 10.0+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+

What is byte array in Swift?

In Swift a byte is called a UInt8—an unsigned 8 bit integer. A byte array is a UInt8 array. In ASCII we can treat chars as UInt8 values. With the utf8 String property, we get a UTF8View collection. We can convert this to a byte array.

What is a ByteArray?

ByteArray is an extremely powerful Class that can be used for many things related to data manipulation, including (but not limited to) saving game data online, encrypting data, compressing data, and converting a BitmapData object to a PNG or JPG file.


1 Answers

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.

like image 96
Matt Gallagher Avatar answered Sep 21 '22 19:09

Matt Gallagher