Jump to content

convert string to hex number


baptistou
 Share

Recommended Posts

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

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...