0

我有一个将数据作为十六进制值返回的设备,例如00 00 00 56 00 00 01 00. 我把它放到一个 NSString 中。我只对将第 3 段和第 4 段转换为双段感兴趣。即只有00 56

http://www.binaryhexconverter.com/hex-to-decimal-converter等网站上,它可以工作并返回我想要的值。

当我尝试使用 NSScanner 时,它不喜欢它只是十六进制代码的一部分。

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

double value = 0.0;

BOOL result = [scanner scanHexDouble:&value];

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

我也尝试过使用strtol(),但没有运气。

有人可以帮忙吗?

4

2 回答 2

1

NSScanner 的那个字符串应该是这样的。这是一个示例代码(它有效。)

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

NSLog(@"Value %@", [NSNumber numberWithDouble:value]);
NSLog(@"Result %c", result);
于 2013-02-05T14:09:03.380 回答
1
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);
于 2013-02-05T14:21:04.777 回答