1

我编写了以下方法来将 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

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

4

1 回答 1

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;
}
于 2012-02-09T17:17:35.840 回答