# How to convert a string to hexadecimal in C

Converting a character array or any string to its respective hexadecimal form is simple. The only thing we have to do is to follow the below steps.

1. Take each character from the string and convert it into its respective ASCII value in order to get the integer, i.e., Decimal value.
2. Next, convert that decimal or ASCII value to Hexadecimal.

### Steps to be followed to convert a decimal value to hexadecimal value:

• The decimal number is divided by 16. Consider the division to be an integer division.
• Make a note of the remainder (in hexadecimal).
• Divide the output(quotient) once again by 16. Consider the division to be an integer division.
• The remainders' digit order from last to first determines the hex value.
• We repeat the above process until the quotient becomes zero when divided by 16.

Note: The Base of 16 system is used in the "Hexadecimal" or simply "Hex" numbering system. Hexadecimal numbers are represented by 16 symbols: 0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Here, (A, B, C, D, E, and F) stand for (10, 11, 12, 13, 14, 15).

For example, consider a character as 'k'; now, let's follow the above steps to get our result.

Initially, we find its respective ASCII value, k's ASCII value, is 107.

107 is a decimal number that must be converted to its hexadecimal form. For converting, we follow the above steps:

Firstly, we modulo divide 107 by 16 to get the remainder.

1. 107%16=11 (remainder)
Then 107/16=6
2. 6%16=6 (remainder)
And 6/16=0 as the quotient is zero, stop the process.

Hexadecimal= 611; since 11 is represented as 'B' in hexadecimal values, we replace 11 with 'B'.

The resultant Hexadecimal value is 6B.

Now, we can implement the program with the help of the above logic.

## Program to convert string to Hexadecimal:

Example 1:

``````#include <stdio.h>
#include <string.h>
int main()
{
unsigned char str, strH;
int i, j;
printf("Enter the string: ");
scanf("%[^\n]s", str);
printf("\nString you entered is: %s\n", str);
memset(strH, 0, sizeof(strH));
for (i = 0, j = 0; i < strlen(str); i++, j += 2) {
sprintf((char*)strH + j, "%02X", str[i]);
}
strH[j] = '\0';

printf("Hexadecimal conversion of the given string is: ");
printf("%s\n", strH);
return 0;
}
``````

Output

Example 2:

``````#include <stdio.h>
#include <string.h>
char *decToHexa(int n)
{
int i = 0;
while (n != 0)
{
int temp = 0;
temp = n % 16;

if (temp < 10) {
i++;
}
else {
i++;
}

n = n / 16;
}

char ans ="";

for (int j = i - 1; j >= 0; j--)
{
}

return ans;
}
int main()
{

char hex ="";
char string;
printf("Enter the string:");
scanf("%s",string);
for (int i=0;i<strlen(string);i++)
{
char ch=string[i];
int tmp =(int)ch;
strcat(hex,decToHexa(tmp));
}