Convert from hex to decimal to C

Here is my code that does the conversion from hex to decimal. Hexadecimal values ​​are stored in an unsigned array of char:

  int liIndex ;
  long hexToDec ;
  unsigned char length[4];

  for (liIndex = 0; liIndex < 4 ; liIndex++)
  {
       length[liIndex]= (unsigned char) *content;
       printf("\n Hex value is %.2x", length[liIndex]);
       content++;
  }
  hexToDec = strtol(length, NULL, 16);

Each element of the array contains 1 byte of information, and I read 4 bytes. When I completed it, here is the result that I get:

 Hex value is 00
 Hex value is 00
 Hex value is 00
 Hex value is 01
 Chunk length is 0

Can someone help me understand the error here. The decimal value must be 1 instead of 0.

Regards, Darkie

+3
source share
2 answers

, % x, , content , . 0 content '\0' '0'?

strtol . content , :

hexToDec = 0;
int place = 1;
for(int i=3; i>=0; --i)
{
  hexToDec += place * (unsigned int)*(content+i);
  place *= 16;
}
content += 4;
+2

strtol . length[0] == '\0', strtol . , "0A21", , {0,0,0,1}, .

content , ? , , .

+2

Source: https://habr.com/ru/post/1739791/


All Articles