NSData到unsigned char *

时间:2013-08-28 03:34:56

标签: objective-c

我需要将NSData转换为类似unsigned char b[16]的内容。这是我到目前为止所做的。

NSData *c = [@"testingsomething" dataUsingEncoding:NSUTF8StringEncoding];
unsigned char *a = (unsigned char *)[c bytes];
NSLog(@"size of a is %ld", sizeof(a));
unsigned char b[16] = "testingsomething";
NSLog(@"size of b is %ld", sizeof(b));

我得到的输出是;

size of a is 4
size of b is 16

我该怎么做?非常感谢帮助。

1 个答案:

答案 0 :(得分:5)

在第一个实例中,sizeof给出了指针的大小,因为你给它一个指针类型的对象。在第二个实例中,它给出了数组的大小,因为您给了sizeof array 类型的对象。在C语言中,指针和数组通常是可以互换的,但它们仍然被认为是不同的类型,并且具有不同的语义。

如果要将字节复制到自己的缓冲区,请使用NSData的{​​{3}}方法。或者,如果您尝试以特定编码获取字符串的字节表示,请查看NSString的{​​{3}}方法。