将unsigned char数组转换为NSData并返回

时间:2011-12-02 10:24:45

标签: iphone objective-c nsdata arrays

如何在目标c中将unsigned char数组转换为NSData?

这是我想要做的,但它不起作用。 Buffer是我的unsigned char数组。

NSData *data = [NSData dataWithBytes:message length:length];

1 个答案:

答案 0 :(得分:62)

您可以使用此NSData类方法

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

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

然后您可以像这样获取数组(如果您知道它是正确的数据类型)

NSUInteger size = [data length] / sizeof(unsigned char);
unsigned char* array = (unsigned char*) [data bytes];