I have an NSData object that contains just <64> which is supposed to represent the int 100 How can I convert this NSData to an int?

I can convert it to it's Chr equivalent d using

NSString *string = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];

but I need the Dec equivalent of 100

Thanks

有帮助吗?

解决方案

<64> means that the NSData object contains a single byte with the value 0x64 = 100, so the following should work;

const uint8_t *bytes = [data bytes]; // pointer to the bytes in data
int value = bytes[0]; // first byte

其他提示

int *b = (int *)data.bytes;
printf("%d",*b); //prints 100

Below logic converts NSData to integer perefctly. Length of bytes does not matter. It just works.

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

unsigned dataAsInt = 0;
NSScanner *scanner = [NSScanner scannerWithString: stringData];
[scanner scanHexInt:& dataAsInt];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top