[英]Objective-C: Convert Hex Strings to Integers to Compare Which is Greater
My goal is to compare two hex strings and determine which number is higher. 我的目标是比较两个十六进制字符串并确定哪个数字更大。 I assume I need to convert those hex strings to integers to be able to compare them mathematically, but the conversion to unsigned
isn't working. 我假设我需要将那些十六进制字符串转换为整数,以便能够在数学上进行比较,但是无法进行unsigned
转换。 Here's what I've tried: 这是我尝试过的:
NSString *firstHex = @"35c1f029684fe";
NSString *secondHex = @"35c1f029684ff";
unsigned first = 0;
unsigned second = 0;
NSScanner *firstScanner = [NSScanner scannerWithString:firstHex];
NSScanner *secondScanner = [NSScanner scannerWithString:secondHex];
[firstScanner scanHexInt:&first];
[secondScanner scanHexInt:&second];
NSLog(@"First: %d",first);
NSLog(@"Second: %d",second);
But the log output gives me: 但是日志输出给了我:
First: -1
Second: -1
I can't figure out what I'm doing wrong. 我不知道我在做什么错。 Am I using NSScanner
correctly here? 我在这里正确使用NSScanner
吗? Thanks in advance. 提前致谢。
Your hex numbers are 13 digits long - 52 binary bits. 您的十六进制数字长13位-52个二进制位。 This is longer than 32 bits, use long long
variables and scanHexLongLong:
instead. 这比32位long long
,请使用long long
变量和scanHexLongLong:
代替。
For the sake of completeness, here's the working code using the advice from the above answer: 为了完整起见,以下是使用上述答案中的建议的工作代码:
NSString *firstHex = @"35c1f029684fe";
NSString *secondHex = @"35c1f029684ff";
unsigned long long first = 0;
unsigned long long second = 0;
NSScanner *firstScanner = [NSScanner scannerWithString:firstHex];
NSScanner *secondScanner = [NSScanner scannerWithString:secondHex];
[firstScanner scanHexLongLong:&first];
[secondScanner scanHexLongLong:&second];
NSLog(@"First: %llu",first);
NSLog(@"Second: %llu",second);
if(first > second){
NSLog(@"First is greater");
}else{
NSLog(@"Second is greater");
}
it must be faster to just find out which one is larger as a string: 找出哪个更大的字符串必须更快:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.