How to Convert String to Hexadecimal and Vice versa

Introduction

This article shows you how to convert string to hexadecimal and vice versa.

I did this program for my smart Card application. Earlier, I was using visual basic coding but this time I have to change my code into C#. Usually smart card application is writing data in hex format. I do not have a good hex converter to help me do those conversions that's why I made this.

Using the code

The main code used for the conversion is from the Microsoft.VisualBasicclass. Below is the code that is used to convert a string to hexadecimal format. We can't direct convert all characters in to hexadecimal format (eg:@#$%^&*()) that's why firstly I take ASCII value of the character, and then convert ASCII value into hexadecimal format.

  1. //For this I made while loop  
  2. while (Data.Length > 0)  
  3. {  
  4.     //first I take each character using substring  
  5.     sValue= Data.Substring(0, 1).ToString()  
  6.     //then convert character into ascii.          
  7.     sValue= Strings.Asc(sValue)  
  8.     //then convert ascii value into Hex Format   
  9.     sValue = Conversion.Hex(sValue)  
  10.     //after converting remove the character.   
  11.     Data = Data.Substring(1, Data.Length - 1);  
  12.     sHex = sHex + sValue;  
  13. }   
Only two functions I used for this application

Data_Hex_Asc(data)

(This Function for Converting data into hex format

  1. public string Data_Hex_Asc(ref string Data)  
  2. {  
  3.     string Data1 = "";  
  4.     string sData = "";  
  5.     while (Data.Length > 0)  
  6.     //first take two hex value using substring.  
  7.     //then convert Hex value into ascii.  
  8.     //then convert ascii value into character.  
  9.     {  
  10.         Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();  
  11.         sData = sData + Data1;  
  12.         Data = Data.Substring(2, Data.Length - 2);  
  13.     }  
  14.     return sData;  
  15. }  
Data_Asc_Hex(data)

(This Function for Converting hex into data )

  1. public string Data_Asc_Hex(ref string Data)  
  2. {  
  3.     //first take each charcter using substring.  
  4.     //then convert character into ascii.  
  5.     //then convert ascii value into Hex Format  
  6.     string sValue;  
  7.     string sHex = "";  
  8.     while (Data.Length > 0)  
  9.     {  
  10.         sValue = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()));  
  11.         Data = Data.Substring(1, Data.Length - 1);  
  12.         sHex = sHex + sValue;  
  13.     }  
  14.     return sHex;  
  15. } 


Similar Articles