문제

I have a device that returns data as a Hex value, for example 00 00 00 56 00 00 01 00. I place this into an NSString. I am only interested in converting the 3rd and 4th segment to a double. ie only 00 56.

On sites such as http://www.binaryhexconverter.com/hex-to-decimal-converter it works and returns me the value I want.

When I try to use NSScanner it doesn't like that it is only a segment of a Hex code.

NSScanner *scanner = [[NSScanner alloc] initWithString:numberAsHex];

double value = 0.0;

BOOL result = [scanner scanHexDouble:&value];

NSLog(@"Value %@", [NSNumber numberWithDouble:value]);
NSLog(@"Result %c", result);

I have also tried to use strtol() as well but no luck.

Could anyone help?

도움이 되었습니까?

해결책

That string for NSScanner should be like this. Here is a sample code (It works.)

NSScanner *scanner = [[NSScanner alloc] initWithString:@"0x0056"];
double value = 0;
BOOL result = [scanner scanHexDouble:&value];

NSLog(@"Value %@", [NSNumber numberWithDouble:value]);
NSLog(@"Result %c", result);

다른 팁

NSString *numberAsHex = @"00 00 00 56 00 00 01 00";
numberAsHex = [numberAsHex stringByReplacingOccurrencesOfString:@" " withString:@""];
numberAsHex = [NSString stringWithFormat:@"%@%@",@"0x",numberAsHex];
NSScanner *scanner = [[NSScanner alloc] initWithString:numberAsHex];
double value = 0.0;
BOOL result = [scanner scanHexDouble:&value];
NSLog(@"Value %@", [NSNumber numberWithDouble:value]);
NSLog(@"Result %d", result);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top