NSData到unsigned char*

Tec*_*163 0 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));
Run Code Online (Sandbox Code Playgroud)

我得到的输出是;

size of a is 4
size of b is 16
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?非常感谢帮助.

dre*_*lax 5

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

如果您想字节复制到自己的缓冲区,可使用NSDatagetBytes:range:方法.或者,如果你想获得一个特定编码字符串的字节表示,看一看NSStringgetBytes:maxLength:usedLength:encoding:options:range:remainingRange:方法.