skydoor
skydoor

Reputation: 25868

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 so that I can insert it into the blob of database.

Can anybody offer any library function to convert the string?

Upvotes: 1

Views: 5862

Answers (2)

Joniale
Joniale

Reputation: 565

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

Upvotes: 1

Constantin
Constantin

Reputation: 8961

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

Upvotes: 3

Related Questions