Write a C program to convert String into Hexadecimal

By | 03.12.2016

C program to convert String into Hexadecimal


Write a C program to convert String into Hexadecimal. This article shows you how to convert string into hexadecimal. Below is the code that is used to convert a string to hexadecimal format.


Hexadecimal


According To Wikipedia, 

In mathematics and computing, hexadecimal (also base 16, or hex) is a positional numeral system with a radix, or base, of 16. It uses sixteen distinct symbols, most often the symbols 09 to represent values zero to nine, and A, B, C, D, E, F (or alternatively a, b, c, d, e, f) to represent values ten to fifteen.

  • Hexadecimal numerals are widely used by computer system designers and programmers. One hexadecimal digit represents a nibble (4 bits), which is half of an octet or byte (8 bits).
  • For example, a single byte can have values ranging from 00000000 to 11111111 in binary form, but this may be more conveniently represented as 00 to FF in hexadecimal.
  • The prefix “0x” is used in C and related languages, where this value might be denoted as 0x2AF3.

In this program we will read a String and convert the string to Hexadecimal String. We will convert each character of the string in it’s equivalent hexadecimal value and insert the converted value in a string and finally print the Hexadecimal String.

Below is the source code of the C program to convert String to Hexadecimal which is successfully compiled and run on the windows system.The Output of the program is shown below.


SOURCE : :


#include <stdio.h>
#include <string.h>
 
int main()
{
    unsigned char str[100],strH[200];
    int i,j;
     
    printf("Enter string: ");
    scanf("%[^\n]s",str);
     
    printf("\nString is: %s\n",str);
     
    /*set strH with nulls*/
    memset(strH,0,sizeof(strH));
     
    /*converting str character into Hex and adding into strH*/
    for(i=0,j=0;i<strlen(str);i++,j+=2)
    { 
        sprintf((char*)strH+j,"%02X",str[i]);
    }
    strH[j]='\0'; /*adding NULL in the end*/
     
    printf("Hexadecimal converted string is: \n");
    printf("%s\n",strH);
     
     
    return 0;
}

Output : :


Enter string: CodezClub

String is: CodezClub
Hexadecimal converted string is:
436F64657A436C7562
5 1 vote
Article Rating
Category: Advance Programs C Programming Tags:

About Tunde A

My name is Tunde Ajetomobi, a Tech Enthusiast and Growth Hacker. I enjoy creating helpful content that solves problem across different topics. Codezclub is my way of helping young aspiring programmers and students to hone their skills and find solutions on fundamental programming languages.

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments