将unsigned char数组转换为NSData并返回 [英] Convert unsigned char array to NSData and back

查看:143
本文介绍了将unsigned char数组转换为NSData并返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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];


推荐答案

你可以使用这个NSData类方法

You can just use this NSData class method

+ (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];

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

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];

这篇关于将unsigned char数组转换为NSData并返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆