# how can i convert hex string into decimal number?

How can a hex string variable be converted into a decimal string? thanks

Slap “0x” on the front and call…
http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

Then call this to convert to a decimal string…
http://www.cplusplus.com/reference/clibrary/cstdlib/itoa/

Is it OK to add this function to Arduino?

``````unsigned long hex2int(char *a, unsigned int len)
{
int i;
unsigned long val = 0;

for(i=0;i<len;i++)
if(a[i] <= 57)
val += (a[i]-48)*(1<<(4*(len-1-i)));
else
val += (a[i]-55)*(1<<(4*(len-1-i)));
return val;
}
``````

Or can i use the following in Arduino?

int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

or

int decValue = Convert.ToInt32(hexValue, 16);

ATmega1280:
Is it OK to add this function to Arduino?
unsigned long hex2int(char *a, unsigned int len)

Yes.

ATmega1280:
Or can i use the following in Arduino?
int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);
int decValue = Convert.ToInt32(hexValue, 16);

Is that C#? No.

Is it OK to add this function to Arduino?

No! No! No!

There are several problems with that code. First, and most obvious is that it does not do proper validation of the input. A space is less than 57, so it would be treated as a valid digit, even though it is not.

Second, the range of valid values should be '0' to '9' and 'a' to 'f' and 'A' to 'F', NOT the ASCII equivalents of those character values!

Third, the code is posted incorrectly, so the array indexing is lost.

http://www.cplusplus.com/reference/clibrary/cstdlib/strtol/

For example:

``````#define EEPROM_MACADDR_START 32