how to convert the string to hex code of the ASCII in C
I have a string like this "Hello"
Now I need to convert it to hex code of the ASCII code for each character s开发者_开发百科o that I can insert it into the blob of database.
Can anybody offer any library function to convert the string?
You can simply format characters to hexcode via sprintf.
#include <stdio.h>
int main(int argc, char* argv[]) {
char buf[255] = {0};
char yourString[255] = { "Hello" };
for (size_t i = 0; i < strlen(yourString); i++) {
sprintf(buf, "%s%x", buf, yourString[i]);
}
printf(buf+ '\n');
return 0;
}
Try this to convert the ascii string/char to a hex representation string.
Very important
if you want to have a correct conversion using the sprintf is to use unsigned char variables. Some char strings come in unicode string format and they need to be first converted to unsigned char
.
#include <stdio.h>
#include <string.h>
int main(void){
unsigned char word[17], unsigned outword[33];//17:16+1, 33:16*2+1
int i, len;
printf("Intro word:");
fgets(word, sizeof(word), stdin);
len = strlen(word);
if(word[len-1]=='\n')
word[--len] = '\0';
for(i = 0; i<len; i++){
sprintf(outword+i*2, "%02X", word[i]);
}
printf("%s\n", outword);
return 0;
}
精彩评论