user3065932
user3065932

Reputation: 103

Convert Ascii number to Hex in C

I use the following function to convert a value in hex to ASCII:

void hex_to_ascii(unsigned char* buf, unsigned char number)
{
  int i;

  sprintf(  buf, "%03d", number );

  printf("\nNumber in Ascii: ");
  for( i=0; i< 3; i++)
     printf("%#04x ", *(buf+i));

  printf("\n");
  return;
}

e.g. If the hex value is 0xff the function generates 0x32 0x35 0x35 which is the Ascii representation of 255.

Now I would like to reverse the operation. I would like a function that can be passed three bytes (array of 3) to generate the hex value.

i.e. We pass 0x32 0x35 0x34 and it generates 0xFE.

Can you please help me with this? It is for an embedded system, the values are not typed they are obtained from a comms buffer.

Many Thanks.

EDIT:

I wrote this and it seems to work..

unsigned char ascii_to_hex(unsigned char* buf)
{
   unsigned char hundred, ten, unit, value;

   hundred = (*buf-0x30)*100;
   ten = (*(buf + 1)-0x30)*10;
   unit = *(buf+2)-0x30;     

   value = (hundred + ten + unit);
   printf("\nValue: %#04x \n", value);

   return value; 
}

Thanks to everyone for replying.

Upvotes: 2

Views: 31375

Answers (2)

abhoriel
abhoriel

Reputation: 103

you can use stdlib's atoi() function to convert a string to an integer:

char str[] = {0x32, 0x35, 0x34, 0x00};
int integer = atoi(str);
printf("%x\n", integer);

you can then printf() that integer as hex/dec or whatever. If this is too simple for your needs, then a more powerful alternative is to use sscanf()

If you are getting these integer strings from a comms buffer then you will likely want to split the buffer up into separate numbers first (perhaps they are separated by spaces for example). A simple way of doing this in C would be to use strtok().

EDIT: this edit is in response to the code that you have added to your question. I cannot comment on your question as I do not have enough reputation! The code you have added is broken. It will only work if a three digit string is provided, eg "001", "255". If a different number of digits are provided, it will read beyond the end of the string and produce garbage output, try "1" or "14", or "12314".

Upvotes: 1

Pandrei
Pandrei

Reputation: 4951

You need to build a number in base10, considering you have all the digits stored in char*buf like so:

//assumtions: n - number of digits
//            digits are ordered MSD first -> buff[0] contains the most significant digit.
 for(i=0;i<n;i++)
    {
       number += buf[n-i-1]*pow(10,i); //number+=digit*10^i
    }

    printf("%x\n", number);

Upvotes: 1

Related Questions