Tech163
Tech163

Reputation: 4286

NSData to unsigned char *

I need to convert NSData to something like unsigned char b[16]. This is what I have so far.

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

The output I get is;

size of a is 4
size of b is 16

How can I do this? Help would be greatly appreciated.

Upvotes: 1

Views: 5326

Answers (1)

dreamlax
dreamlax

Reputation: 95335

In the first instance, sizeof is giving you the size of a pointer, because you are giving it an object that is a pointer type. In the second instance, it is giving you the size of an array because you are giving sizeof an object of array type. In C, pointers and arrays are often interchangeable but they are still considered distinct types and have distinct semantics.

If you want to copy bytes to your own buffer, use NSData's getBytes:range: method. Or, if you are trying to get the byte representation of a string in a specific encoding, have a look at NSString's getBytes:maxLength:usedLength:encoding:options:range:remainingRange: method.

Upvotes: 6

Related Questions