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?
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+
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With