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

时间:2012-02-09 17:13:44

标签: iphone objective-c ios hex strtol

我编写了以下方法将Hex String转换为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;
}

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

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

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

1 个答案:

答案 0 :(得分: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;
}