[英]Convert a segment of an Hex string to a double
I have a device that returns data as a Hex value, for example 00 00 00 56 00 00 01 00
. 我有一个设备将数据作为十六进制值返回,例如
00 00 00 56 00 00 01 00
。 I place this into an NSString. 我将它放入NSString中。 I am only interested in converting the 3rd and 4th segment to a double.
我只对将第3和第4段转换为双倍感兴趣。 ie only
00 56
. 即只有
00 56
。
On sites such as http://www.binaryhexconverter.com/hex-to-decimal-converter it works and returns me the value I want. 在http://www.binaryhexconverter.com/hex-to-decimal-converter这样的网站上,它可以运行并返回我想要的值。
When I try to use NSScanner it doesn't like that it is only a segment of a Hex code. 当我尝试使用NSScanner时,它不喜欢它只是Hex代码的一部分。
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. 我也尝试过使用
strtol()
,但没有运气。
Could anyone help? 有人可以帮忙吗?
That string for NSScanner should be like this. NSScanner的字符串应该是这样的。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.