[英]How to convert a string to hex and vice versa in c?
如何在c中將字符串轉換為十六進制,反之亦然。 例如:,像“謝謝你”到十六進制格式的字符串:7468616e6b20796f75並且從十六進制7468616e6b20796f75到字符串:“謝謝”。 有沒有辦法做到這一點?
提前致謝
sprintf
和sscanf
就足夠了。
#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;
}
現在
$ ./a.out
'thank you' in hex is 7468616e6b20796f75.
7468616e6b20796f75 as a string is 'thank you'.
要將字符串轉換為十六進制代碼:
#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.