×

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.

Therefore, k is represented ad 6B in hexadecimal form.

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[100], strH[200];
    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

How to convert a string to hexadecimal in c

Example 2:

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


		if (temp < 10) {
			hexaDeciNum[i] = temp + 48;
			i++;
		}
		else {
			hexaDeciNum[i] = temp + 55;
			i++;
		}


		n = n / 16;
	}


	char ans[100] ="";


	for (int j = i - 1; j >= 0; j--)
	{
	    char add[100]={hexaDeciNum[j]};
		strcat(ans,add);
	}


	return ans;
}
int main()
{


char hex[100] ="";
char string[10];
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));
	}
	printf("The Hexadecimal form is %s",hex);
	return 0;
}

Output

How to convert a string to hexadecimal in c

Therefore, we have seen two programs for the implementation of the above problem. Although two programs produce the same output and are used for the same cause, the way they produce the output is completely different from each other.

The fundamental benefit of using hexadecimal numbers is that they require less memory to hold more numbers; for instance, they can store 256 numbers in two digits, as opposed to 100 for decimal numbers. Computer memory addresses are also represented by this numeric format. Any binary digit may be represented using only 4 bits, and converting between Hexadecimal and binary is simple. Input and output are simpler to manage in hexadecimal format.

The fields of data science, artificial intelligence, and machine learning all have many benefits. It is also used in colour references, Assembly language programs, Error messages and Media Access Control (MAC) addresses. Also, it can be used to represent numbers kept in a CPU's registers or in main memory, as well as during the debugging phase of programming.

Hexadecimal's main drawback is that it can be challenging for individuals to read and write, and doing operations like multiplications and divisions with it can be challenging. Also, the most challenging number system for working with computer data is hexadecimal.


Related Topics

Addition of Matrix in C

The mathematical operation of includingor greater matrices is called the addition of matrices. A matrix is a square series of numbers, symbols, words, letters, and different things. In this article,...

3 minutes read.

Heap Sort in C

In this tutorial, we will learn about heap sorting in C language, but before going to Heap sort, we have to know the concept of Complete Binary Tree. What is Complete...

8 minutes read.

Header files in C

Header files in C In the C programming language, header files are present, which have an extension of ‘.h’, and it consists of macro definitions, declarations, and so on that are...

4 minutes read.

C pre-processor

The C processor is a macro processor which is used to compile the source code of the program (step by step) . It is not a part of the compiler....

4 minutes read.

Strcpy() in C

In C language many operations can be performed on a string. Characters in a sequence are known as string. Note:   To use this function we must include the #include<string.h> header file...

4 minutes read.

Diffie-Hellman Algorithm in C

Background: A method of public-key encryption known as elliptic curve cryptography (ECC) is based on the algebraic structure of elliptic curves over finite fields. To ensure equal security, ECC encryption requires fewer...

4 minutes read.

Errors in C

Errors in C Errors are nothing but problems or faults that pretty much occur in all the programming languages. Errors make the behavior of the program seem abnormal, and even the...

4 minutes read.

Sum of N numbers in C using For loop

Before we move on the program of sum of N numbers, first we have to know about the For Loop statement. The syntax of ‘for’ loop in C programming language is...

3 minutes read.

Exit control loop in C

To examine the termination condition for an exit, we usually use an exit control loop in C. If the evaluation for termination condition results in true, then the control would...

3 minutes read.

Reverse a Stack using Recursion in C

In this tutorial we will learn how recursion will be used in this case to reverse a stack. For loops, while loops, do-while loops, and similar constructions are not permitted....

5 minutes read.

Example of Iteration in C

The iterations in the C language are the statements which are executed number of times until a certain condition is reached. These iterations are regarded as “Loops” in C language....

3 minutes read.

C Program to find the size of a File

Before knowing about the Program, you need to understand what the size of a file is. After that, you should know how it is going to work with the given...

4 minutes read.

Character Class Tests in C

Introduction The <ctype.h> is a header file in C which is used to declare functions for testing characters. This header file of the C standard library is used to declare multiple...

4 minutes read.

GCD of Two Numbers in C

The GCD means the greatest common divisor of two or more integers, it is also called as hcf. The gcd returns the greatest integer of the given two integers that...

3 minutes read.

fflush in C

In this article, we will understand what is fflush(), the need for fflush and fflush(stdin), and fflush(stdout). The fflush() function is used to clear the output buffer and move the buffered...

3 minutes read.

Fibonacci series program in C using Recursion

In this tutorial, we’ll explore how to utilise recursion to build the Fibonacci sequence in C language. What does the term "Fibonacci Series" mean? The following number in a Fibonacci number series is...

2 minutes read.

Write a program that produces different results in C and C++

In this tutorial, we'll explore several programs that, depending on whether they are developed using C or C++ compilers, will produce varying outputs. There are numerous similar programs, but we will just...

2 minutes read.

Operators in C

An operator is a special symbol that tells the compiler to perform specific mathematical or logical operations. It is the combination of constants and variables through expressions. Example: int c = a+b*5 Where,...

5 minutes read.

7 Best IDEs for C/C++ Developers in 2024

As we all know that in programming languages, C is known as the building block which cannot be contradicted, and C++ is the prolong kind of C and it can...

4 minutes read.

Typecast vs. typedef in C

Typecast vs. typedef in C Typecast In the C programming language, converting the data type from one form to another is known as type casting or the type conversion. It is a...

5 minutes read.