Converting NSdata to bytes & then converting the f

2019-03-11 13:24发布

I've an NSData object, First I want to convert NSData object to bytes, then read the first four bytes in this NSData object & then convert the first four bytes to their equivalent integer values. Any ideas on how to go about this?

How about converting all the four bytes to a single positive integer value?

3条回答
Melony?
2楼-- · 2019-03-11 13:40

Getting an int out of raw data is ambiguous: where does the data come from? What size do you want your int? Do you want them signed or unsigned? What byte ordering do you expect?

So here is one scenario: the data you get is from a stream encoded by an external process that feeds 32-bit signed ints in big-endian order. Here's how you could do it:

NSData *dataFromStream = functionThatReturnsNSData();
SInt32 *signedInt32pointer = [dataFromStream bytes];
SInt32 unSwappedInt32 = *signedInt32pointer;
SInt32 reorderedInt32 = CFSwapInt32BigToHost(unSwappedInt32);

RTFM the Byte ordering and byte swapping sections of the Memory Management Programming Guide for Core Foundation.

查看更多
在下西门庆
3楼-- · 2019-03-11 13:42

That's quite simple. Use bytes to get at the bytes and then cast to unsigned char*

unsigned char *n = [yourNSData bytes];
int value1 = n[0];
int value2 = n[1];
int value3 = n[2];
int value4 = n[3];

Update

To turn this into a single int assumes bytes contains a valid int:

int result = *(int *)n;
查看更多
欢心
4楼-- · 2019-03-11 13:44
int n ; // first n bytes
NSData *data; // your data

NSData *subData = [data subdataWithRange:NSMakeRange(0, n)]; // make sure if data has n bytes

NSString *stringData = [subData description];
stringData = [stringData substringWithRange:NSMakeRange(1, [stringData length]-2)];

unsigned dataAsInt = 0;
NSScanner *scanner = [NSScanner scannerWithString: stringData];
[scanner scanHexInt:& dataAsInt];
查看更多
登录 后发表回答