Newbie to C programming here. I am trying to convert a char array into individual hex values and store them in an unsigned char array. Basically I have "3www6google3com0" and I would like to get the 8 bit hex value for each individual character from the string. I would like to end up with an unsigned char array of something of the sort like:

unsigned char foo[100] = {
0x03, 0x77, 0x77, 0x77 .... etc.
}

I've been playing around with itoa, sprintf, and sscanf but am not getting the results I want. Thanks in advance for any help!

-BtL

In essence your char array already has "hex" values in it, or decimal numbers or characters or however you wish to imagine them. Transferring them to another (unsigned char) array will not really change anything.

You should post what code you have to clarify your question.
(BTW, 0x03 is not the hex code for the character '3', it's 0x33.)

Assuming that you want to print out or store the 8bit hex values of each character of the input string I am giving these guidelines.

Firstly take the input into an array by name str[30] may be.
Let the final array be:
unsigned char foo[30][30];

Now convert every one of the characters in the input string into their hex values and store it in an array of array of character strings as :

for(i=0;i<strlen(str);i++)
{
        // Alteration
        foo[i][0]='0';
        foo[i][1]='x';
        itoa(str[i],&foo[i][2],16);
}

If you want three to be treated as 3 and not '3' then you can alter the code by placing this statement in place of "//Alteration" in for loop:

if(isdigit(str[i])) str[i]=str[i]-'0';

But ya as nucleon said every number will be stored as a hex constant itself this would be one of the process to store those hex values somewhere else in the format:
0x<8bit hex value>

Hope this helps !!! :)

Ok this clarifies things.

if(isdigit(str[i])) str[i]=str[i]-'0';

was exactly what I needed to treat the numerical chars in the string as their decimal value. Thank you both for your responses!

This article has been dead for over six months. Start a new discussion instead.