34

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];
Ren
  • 1,111
  • 5
  • 15
  • 24
Bewn
  • 575
  • 4
  • 9
  • 13

1 Answers1

71

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];
jbat100
  • 16,757
  • 4
  • 45
  • 70
  • When i want to get the array back, does this really work? I cant see you assigning the array to something? – Bewn Dec 02 '11 at 10:47
  • It's assigned, on the last line. But `[NSData bytes]` gives untyped results, so it needs to be cast to the type you're looking after. – Cyrille Dec 02 '11 at 10:51
  • 1
    The first section actually copies the unsigned chars into the NSData (if you don't want that you can use `+ (id)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length` instead), the second just gets a pointer to that data, it does not copy it back. – jbat100 Dec 02 '11 at 10:54
  • 1
    Should the last line not be: unsigned char* array = (unsigned char*) [data bytes]; ? It had me puzzled for a min – Rambatino May 18 '14 at 22:25
  • 1
    @MarkRamotowski well spotted, I don't know it escaped the attention of everyone for over 2 years... Rectified now. – jbat100 May 20 '14 at 09:06