【问题标题】:Convert a segment of an Hex string to a double将十六进制字符串的一段转换为双精度
【发布时间】:2013-02-05 13:55:50
【问题描述】:

我有一个将数据作为十六进制值返回的设备,例如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(),但没有成功。

有人可以帮忙吗?

【问题讨论】:

  • 此时结果返回0.000
  • 你想要来自这个字符串369367187712的这个@"0000005600000100
  • 这个“设备”是否使用与 iPhone/iPad 相同的 endianness

标签: ios objective-c hex double strtol


【解决方案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);

【讨论】:

  • 你应该分开要转换的十六进制字符串
  • 这行得通,我所要做的就是把空格去掉就行了。
【解决方案2】:
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);

【讨论】:

    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2019-08-13
    • 2019-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-14
    相关资源
    最近更新 更多