Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex to Decimal conversion in C

Tags:

c

decimal

hex

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 value 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

like image 649
name_masked Avatar asked Nov 24 '25 12:11

name_masked


2 Answers

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;
like image 198
user168715 Avatar answered Nov 26 '25 20:11

user168715


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.

like image 22
sblom Avatar answered Nov 26 '25 19:11

sblom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!