[英]Converting char array to int with strtol() in C
i have a difficulty with strtol() function in C, here's a piece of code of how i'm trying to use it 我在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);
So the question is why does strtol() returns 0 ? 所以问题是为什么strtol()返回0? And how do i convert char array of values in hex to int (long in this particular case)?
以及如何将十六进制值的char数组转换为int(在这种情况下较长)? hexVoltage in my case contains {03, 34} after memcpy().
在我的情况下,hexVoltage在memcpy()之后包含{03,34}。 Thanks in advance.
提前致谢。 Really appreciate the help here.
非常感谢您的帮助。
strtol
and friends expect that you supply them with a printable, ASCII representation of the number. strtol
和朋友希望您为他们提供数字的可打印ASCII表示形式。 Instead, you are supplying it with a binary sequence that is read from the file (port). 而是为它提供了从文件(端口)读取的二进制序列。
In that case, your intVoltage
can be computed by combining the two read bytes into a 2-byte number with bitwise operations, depending on the endianness of these numbers on your platform: 在这种情况下,可以通过按位运算将两个读取的字节合并为2字节数字来计算
intVoltage
,具体取决于平台上这些数字的字节序:
uint8_t binVoltage[2];
...
uint16_t intVoltage = binVoltage[0] | (binVoltage[1] << 8);
/* or */
uint16_t intVoltage = (binVoltage[0] << 8) | binVoltage[1];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.