使用C中的strtol()将char数组转换为int

时间:2016-09-09 11:46:21

标签: c strtol

我在C中遇到strtol()函数有困难,这里是我试图使用它的一段代码

char   TempChar;                        
char   SerialBuffer[21];
char   hexVoltage[2];
long   intVoltage;

 do
   {
     Status = ReadFile(hComm, &TempChar, sizeof(TempChar), &NoBytesRead, NULL);
     SerialBuffer[i] = TempChar;
     i++;
    }
  while (NoBytesRead > 0);

memcpy(hexVoltage, SerialBuffer+3, 2);

intVoltage = strtol(hexVoltage, NULL, 16);

所以问题是为什么strtol()返回0?我如何将十六进制值的char数组转换为int(在这种特殊情况下长)?在我的情况下,hexVoltage在memcpy()之后包含{03,34}。 提前致谢。非常感谢这里的帮助。

1 个答案:

答案 0 :(得分:1)

strtol和朋友们希望您为他们提供数字的可打印的ASCII表示形式。相反,您正在为它提供从文件(端口)读取的二进制序列。

在这种情况下,可以通过将两个读取字节组合成一个2字节数字和逐位运算来计算intVoltage,具体取决于平台上这些数字的字节顺序:

uint8_t binVoltage[2];
...
uint16_t intVoltage = binVoltage[0] | (binVoltage[1] << 8);
/* or */
uint16_t intVoltage = (binVoltage[0] << 8) | binVoltage[1];
相关问题