开发者

Hex to Decimal conversion in C

开发者 https://www.devze.com 2022-12-25 20:54 出处:网络
Here is my code which is doing the conversion from hex to decimal. The hex values are stored in a unsigned char array:

Here is my code which is doing the conversion from hex to decimal. The hex values are stored in a unsigned char array:

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

  for (liIndex = 0; liIndex < 4 ; liIndex++)
  {
       length[liIndex]= (unsigned char) *content;
       printf("\n Hex va开发者_运维知识库lue is %.2x", length[liIndex]);
       content++;
  }
  hexToDec = strtol(length, NULL, 16);

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

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

Can any one please help me understand the error here. Th decimal value should have come out as 1 instead of 0.

Regards, darkie


My guess from your use of %x is that content is encoding your hexademical number as an array of integers, and not an array of characters. That is, are you representing a 0 digit in content as '\0', or '0'?

strtol only works in the latter case. If content is indeed an array of integers, the following code should do the trick:

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


strtol is expecting a zero-terminated string. length[0] == '\0', and thus strtol stops processing right there. It converts things like "0A21", not things like {0,0,0,1} like you have.

What are the contents of content and what are you trying to do, exactly? What you've built seems strange to me on a number of counts.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号