Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert unsigned char array to NSData and back

How do you convert an unsigned char array to an NSData in objective c?

This is what I am trying to do, but it doesn't work. Buffer is my unsigned char array.

NSData *data = [NSData dataWithBytes:message length:length];
like image 612
Bewn Avatar asked Dec 02 '11 10:12

Bewn


1 Answers

You can just use this NSData class method

+ (id)dataWithBytes:(const void *)bytes length:(NSUInteger)length

Something like

NSUInteger size = // some size
unsigned char array[size];
NSData* data = [NSData dataWithBytes:(const void *)array length:sizeof(unsigned char)*size];

You can then get the array back like this (if you know that it is the right data type)

NSUInteger size = [data length] / sizeof(unsigned char);
unsigned char* array = (unsigned char*) [data bytes];
like image 193
jbat100 Avatar answered Oct 25 '22 14:10

jbat100