문제

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