Here is How to Convert String to Hexadecimal and Vice versa

This article shows you how to convert string to hexadecimal and vice versa.
Image result for How to Convert String to Hexadecimal and Vice versaI 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.VisualBasic class. 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.

//For this I made while loop
while (Data.Length > 0)
{
//first I take each character using substring
sValue= Data.Substring(0, 1).ToString()
//then convert character into ascii.
sValue= Strings.Asc(sValue)
//then convert ascii value into Hex Format
sValue = Conversion.Hex(sValue)
//after converting remove the character.
Data = Data.Substring(1, Data.Length – 1);
sHex = sHex + sValue;
}

Ony two functions I used for this application

Data_Hex_Asc(data)

(This Function for Converting data into hex format

public string Data_Hex_Asc(ref string Data)
{
string Data1 = “”;
string sData = “”;
while (Data.Length > 0)
//first take two hex value using substring.
//then convert Hex value into ascii.
//then convert ascii value into character.
{
Data1 = System.Convert.ToChar(System.Convert.ToUInt32(Data.Substring(0, 2), 16)).ToString();
sData = sData + Data1;
Data = Data.Substring(2, Data.Length – 2);
}
return sData;
}

Data_Asc_Hex(data)

(This Function for Converting hex into data )

public string Data_Asc_Hex(ref string Data)
{
//first take each charcter using substring.
//then convert character into ascii.
//then convert ascii value into Hex Format
string sValue;
string sHex = “”;
while (Data.Length > 0)
{
sValue = Conversion.Hex(Strings.Asc(Data.Substring(0, 1).ToString()));
Data = Data.Substring(1, Data.Length – 1);
sHex = sHex + sValue;
}
return sHex;
}
Share on Google Plus

0 comments:

Post a Comment