1

I have a string like this "Hello"

Now I need to convert it to hex code of the ASCII code for each character so that I can insert it into the blob of database.

Can anybody offer any library function to convert the string?

2 Answers 2

3

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;
}
2
  • This is great if all you want to do is have the very last character in your string converted to a hex character in a buffer Apr 20, 2018 at 15:19
  • 1
    @BackDoorNoBaby The answer was just written to illustrate that this library function can be used for this purpose. Please find the updated answer with complete code example that converts the complete string to hex.
    – Constantin
    Apr 23, 2018 at 2:01
1

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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.