Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top