2

How can i convert a string to hex and vice versa in c. For eg:, A string like "thank you" to hex format: 7468616e6b20796f75 And from hex 7468616e6b20796f75 to string: "thank you". Is there any ways to do this ?

Thanks in advance

Developers Staff
  • 75
  • 1
  • 3
  • 10

2 Answers2

5

sprintf and sscanf are good enough for this.

#include <stdio.h>
#include <string.h>

int main(void) {
  char text[] = "thank you";
  int len = strlen(text);

  char hex[100], string[50];

  // Convert text to hex.
  for (int i = 0, j = 0; i < len; ++i, j += 2)
    sprintf(hex + j, "%02x", text[i] & 0xff);

  printf("'%s' in hex is %s.\n", text, hex);

  // Convert the hex back to a string.
  len = strlen(hex);
  for (int i = 0, j = 0; j < len; ++i, j += 2) {
    int val[1];
    sscanf(hex + j, "%2x", val);
    string[i] = val[0];
    string[i + 1] = '\0';
  }

  printf("%s as a string is '%s'.\n", hex, string);

  return 0;
}

Now

$ ./a.out
'thank you' in hex is 7468616e6b20796f75.
7468616e6b20796f75 as a string is 'thank you'.
Gene
  • 46,253
  • 4
  • 58
  • 96
  • I am trying to create an aes decryption script by passing a hex string and decode it as a string. Is there any aes working decryption script that you know ? – Developers Staff Sep 14 '17 at 04:50
  • This answer assumes an ASCII (or compatible) character set. Admittedly, that is pretty common in practice, but it is not required by the C standard. – Peter Sep 14 '17 at 07:14
  • If `text[i] < 0`, `sprintf(hex + j, "%02x", text[i]);` is an issue. Better to insure only non-negative values are passed. Code lacks bounds checking - yet does illustrate the general idea. – chux - Reinstate Monica Sep 14 '17 at 13:27
1

To convert a string to its hexadecimal code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main( )
{
    int i;
    char word[] = "KLNCE";
    char hex[20];
    for ( i = 0; i < strlen ( word ); i++ )
    {
        char temp[5];
        sprintf( temp, "%X", word[i] );
        strcat( hex, temp );
    }
    printf( "\nhexcode: %s\n", hex );
    return 0
}

OUTPUT

hexcode: 4B4C4E4345
UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
Gues
  • 11
  • 1