简体   繁体   中英

How to convert a string to hex and vice versa in c?

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

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'.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM