문제

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. 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? Thanks in advance.

도움이 되었습니까?

해결책

Your hex numbers are 13 digits long - 52 binary bits. This is longer than 32 bits, use long long variables and scanHexLongLong: instead.

다른 팁

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:

  1. the longer string is bigger (ignoring leading 0's)
  2. if they are the same then you can convert each char and compare, Repeat for each char...
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top