Convert a char array of HEX to ASCII in C

C

This function solves the case when we have a message which is represented as sequence of bytes in hex format in a string and we want to convert it back.

void hex_to_string(uint8_t* msg, size_t msg_sz, uint8_t* hex, size_t hex_sz)
{
   memset(msg, '\0', msg_sz);
   if (hex_sz % 2 != 0 || hex_sz/2 >= msg_sz)
      return;

   for (int i = 0; i < hex_sz; i+=2)
   {
      uint8_t msb = (hex[i+0] <= '9' ? hex[i+0] - '0' : (hex[i+0] & 0x5F) - 'A' + 10);
      uint8_t lsb = (hex[i+1] <= '9' ? hex[i+1] - '0' : (hex[i+1] & 0x5F) - 'A' + 10);
      msg[i / 2] = (msb << 4) | lsb;
   }
}
..
..
..
uint8_t hex_representation[] = "48656c6c6f20746865726520446576636f6f6e7321";
uint8_t actual_message[22];

hex_to_string(actual_message, 22, hex_representation,  42);
..
..
..

Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags