将Hex String转换为int时的结果很奇怪

Heb*_*Lau 1 iphone hex objective-c strtol ios

我编写了以下方法将Hex字符串转换为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;
}
Run Code Online (Sandbox Code Playgroud)

大部分时间它都能正常工作,但有时会遇到这样的大麻烦:

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
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我的代码有什么问题?

dus*_*uff 5

您正在将指向单个字符的指针传递给strtol(),而不是以NUL结尾的字符串,因此strtol()有时读取超出您给出的字符.(例如,"1033"是它找到"409"的结果,而不仅仅是"4".)

固定:

-(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;
}
Run Code Online (Sandbox Code Playgroud)