Reputation: 71
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
Upvotes: 2
Views: 21774
Reputation: 161
straight forward solution:
public static string ToHex(string str)
{
byte[] bytes = Encoding.UTF8.GetBytes(str);
return Convert.ToHexString(bytes);
}
to convert back to plain text:
public static string FromHex(string str)
{
byte[] bytes = new byte[str.Length / 2];
for (int i = 0; i < bytes.Length; i++)
bytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
return Encoding.UTF8.GetString(bytes);
}
caller:
string hex = ToHex("my name is moe");
returns: 6D79206E616D65206973206D6F65
string val = FromHex(hex);
Upvotes: 0
Reputation: 11
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
Upvotes: 1
Reputation: 47020
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'.
Upvotes: 5