convert string to hex number

Hi all there,

A quite small question: is there a simple way to convert a string into a number? On google I’ve seen plenty of stuff with the atoi function but it doesn’t seem to work with me.

I have a string that looks like this: “0xA3” and want to put that A3 hexadecimal value into a u8 number.

Anyone can help?

Best regards

Baptistou

On google I’ve seen plenty of stuff with the atoi function but it doesn’t seem to work with me.

I have a string that looks like this: “0xA3” and want to put that A3 hexadecimal value into a u8 number.

0xA3 is hex, you’ll need and integer string like “163” for atoi() to work for you. But if you are going to do that, you might as well just write a hextoi() function yourself.

Here is a simple conversion that will take a two digit hex string in the format “0xHH” and convert it to an int:

#include <ctype.h>


int hextoi(const char * valstr) {


	char valchr[3];

	strncpy(valchr, &valstr[2], 3);

	valchr[0] = toupper(valchr[0]);

	valchr[1] = toupper(valchr[1]);


	int result = 0;

	int positionValue = 1;


	for (int i = 1; i >= 0; i--) {

		int valc = 0;

		if (isalpha(valchr[i])) {

			valc = (int)valchr[i] - (int)'A' + 10;

		}

		else if (isnumber(valchr[i])) {

			valc = (int)valchr[i] - (int)'0';

		}


		result += (valc * positionValue);

		positionValue = positionValue << 4;

	}


	return result;

}


int main (int argc, char * const argv[]) {


	int result = hextoi("0xa3");


	printf("%d", result);

}

If you want a char value result, it’s easy to convert this function to do that.

For STM32/MIOS32 I’m normaly using strtol since it allows to differ between decimal and hexadecimal values.

here an example:

/////////////////////////////////////////////////////////////////////////////
// help function which parses a decimal or hex value
// returns >= 0 if value is valid
// returns -1 if value is invalid
/////////////////////////////////////////////////////////////////////////////
static s32 get_dec(char *word)
{
if( word == NULL )
return -1;

char *next;
long l = strtol(word, &next, 0);

if( word == next )
return -1;

return l; // value is valid
}
[/code]









You have to add "#include \<string.h\>" to the header of your .c file







Best Regards, Thorsten.

Thanks guys, I’ve spend the whole day programming yesterday and couldn’t write more smart stuff by the end of the day. This saves me a lot of time!

Baptistou