Search code examples
cstrtol

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

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 ? And how do i convert char array of values in hex to int (long in this particular case)? hexVoltage in my case contains {03, 34} after memcpy(). Thanks in advance. Really appreciate the help here.


Solution

  • strtol and friends expect that you supply them with a printable, ASCII representation of the number. 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:

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