×

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

File Handling in C

File Handling is used to open, read, write, search and close file.  C files I/O functions handles data on secondary storage device. File handling function: There are varioushandling functions in C. Function Operation fopen() It is...

4 minutes read.

Assert() Function in C

Assert (): In C, the statements are executed with the exit statement. In C language declare, and it tests the condition parameters. If the statement executed will be false, it...

3 minutes read.

Difference between while and for loop in C

While Loop The syntax that can be used for the ‘while’ loop in the C programming language is mentioned below: while (test expression or termination condition)  {   // the main body of the...

6 minutes read.

Union in C

Union is a user-defined data type that is used to hold the different types of elements like structure. In union, all members share the same memory location. Syntax: union [union name] { ...

1 minute 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.

How to use Typedef Struct in C

The “typedef” is a predefined keyword in C programming language which is used to declare the new name to an existing type of variable. For better understanding, if you declare a...

3 minutes read.

C Program to Find Largest Number Using Dynamic Memory Allocation

This tutorial will teach us how to locate the highest number a user has ever input into a dynamically allocated memory. C Program: #include <stdio.h> #include <stdlib.h> int main ()  {   int no;   double *data_n;   printf...

1 minute read.

Function in C

Function is a group of statements that are used to perform any task. In other words, we can say that a function is a self- contained a block of programs...

3 minutes read.

Stdio.h in C

Header files are used to make the programmer’s efforts a lot easier. In order to make the programming simple, there are a number of libraries which are included as predefined...

4 minutes read.

C Token

C Token and Keyword The C tokens are the basic buildings blocks in C language which are constructed together to write a C program. Each and every smallest individual unit in the C program is...

2 minutes read.

Infix to Postfix program in C

Infix Expression: In infix expression, an operator is placed between the two operands. Example: x + y, here operator + is placed between operands x and y. Postfix Expression: In...

3 minutes read.

Armstrong program in C using function

In this article we will learn how to find Armstrong of a number using function in C. An Armstrong number is a three-digit number that is the sum of its separate...

1 minute 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.

How to include graphics.h in C?

How to include graphics.h in code blocks? Graphics .h is a header that allows drawing lines, rectangles, ovals, arcs, polygons, pictures, and strings on a graphical window by giving access to...

6 minutes read.

Passing Array to Function in C

Need to pass Arrays? The need to pass arrays to a function arises when we need to pass a list of values to a given function. During the course of our programming...

4 minutes read.

Exponential() in C

Introduction: In C language, there are available many types of functions. The exponential() function is one of them. It is a mathematical function. This article describes using the pow() property to...

3 minutes read.

How to Avoid Structure Padding in C

Generally, when an object of some structure type is declared, some contiguous memory will be allocated in block form, which will be allocated to structure members. To understand structure padding...

3 minutes read.

OpenGL in C

OpenGL stands for Open Graphics Library. It is a low-level, widely supported modeling and rendering software package that is widely available across all the platforms. It is an API used...

4 minutes read.

How to measure time taken by a function in C?

Measuring the time taken by a function is quite a complex task, because numerous methods are frequently not transferable to other platforms, measuring the execution time of a C programs...

5 minutes read.

Limitations of Synchronisation and Uses of Static Synchronisation in Multithreading

The multithreading component of java is the element around which the idea rotates as it permits simultaneous execution of at least two program pieces for the most significant usage of...

9 minutes read.