views:

427

answers:

2

Hi All,

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

+2  A: 

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.

sblom
*content is actually storing the contents of a PNG file. I am reading the number of bytes based on the PNG file format. So here, the length of a chunk is 4 bytes long and so I am storing the 4 bytes in a char array. Does it seem to be something wrong?
darkie15
+2  A: 

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;
content is storing all the contents of the file that I am reading. Can you please help me out using the length array and not manipulating the 'content' variable?
darkie15
Well there's not much point reading content into length, and then using length, rather than using content directly. I've modified my code to more closely match with what you're doing.
thanks a ton .. that works great !!..
darkie15
there seems to be something wrong with this code... it does not interpret the value all the time .. Will try to find out the reason ... Undoing the 'correct answer' !!
darkie15
the code returns -ve decimal values resulting in seg fault !!
darkie15
The code makes several assumptions which may or may not hold; however if you understand the basic algorithm you should be able to easily adapt it to your needs.Some assumptions to get you started:1) content contains only characters '\0' through '\16'.2) hexToDec is large enough to hold a 32-bit positive integer (unsigned int should work on most modern platforms).
Hi ,It is not able to convert the hex value 00 00 29 C9 . Any reason why ?
darkie15
Hi,Got the fix.. Thanks a lot ..!!
darkie15