Question

I coded the following method to convert a Hex String to a int:

-(long)intFromHexString:(NSString*) string
{
  char tempChar;
  int temp;
  tempChar=[string characterAtIndex:[string length]-1];
  temp=strtol(&tempChar, NULL, 16);
  NSLog(@"***>%c = %i",tempChar,temp);
  return temp;
}

Most of the time it works properly but sometimes it really gets into big trouble like this:

2012-02-10 01:09:28.516 GameView[7664:f803] ***>7 = 7
2012-02-10 01:09:28.517 GameView[7664:f803] ***>7 = 7
2012-02-10 01:09:28.518 GameView[7664:f803] ***>D = 13
2012-02-10 01:09:28.519 GameView[7664:f803] ***>5 = 5
2012-02-10 01:09:28.520 GameView[7664:f803] ***>5 = 5
2012-02-10 01:09:28.520 GameView[7664:f803] ***>D = 13
2012-02-10 01:09:28.521 GameView[7664:f803] ***>4 = 4
2012-02-10 01:09:28.522 GameView[7664:f803] ***>4 = 4
2012-02-10 01:09:28.522 GameView[7664:f803] ***>5 = 5
2012-02-10 01:09:28.523 GameView[7664:f803] ***>4 = 1033  <------this
2012-02-10 01:09:28.524 GameView[7664:f803] ***>C = 12
2012-02-10 01:09:28.524 GameView[7664:f803] ***>B = 11
2012-02-10 01:09:28.525 GameView[7664:f803] ***>3 = 3
2012-02-10 01:09:28.526 GameView[7664:f803] ***>3 = 48    <------this
2012-02-10 01:09:28.527 GameView[7664:f803] ***>B = 11

Can anyone tell me what's wrong with my code?

Was it helpful?

Solution

You are passing a pointer to a single character into strtol(), rather than a NUL-terminated string, so strtol() is sometimes reading beyond the character you gave it. (For instance, "1033" is the result of it finding "409", rather than just "4".)

Fix:

-(long)intFromHexString:(NSString*) string
{
  char tempChar[2];
  int temp;
  tempChar[0]=[string characterAtIndex:[string length]-1];
  tempChar[1] = 0;
  temp=strtol(tempChar, NULL, 16);
  NSLog(@"***>%c = %i",tempChar[0],temp);
  return temp;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top