[英]Converting char * to int with strtol only if it's a valid number
[英]Converting char array to int with strtol() in C
我在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}。 提前致謝。 非常感謝您的幫助。
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];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.