1

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.

Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128
  • That's a seven byte integer. Are you sure that there isn't overflow? What happes if you try it with half length strings (3 byte ints)? – Linuxios Jan 16 '14 at 00:28

3 Answers3

6

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

Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
CRD
  • 52,522
  • 5
  • 70
  • 86
0

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");
}
Clifton Labrum
  • 13,053
  • 9
  • 65
  • 128
0

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...
Grady Player
  • 14,399
  • 2
  • 48
  • 76