GeorgePotter
GeorgePotter

Reputation: 899

How to convert a regular string to an ASCII hexadecimal string in C#?

I was recently working on a project where I needed to convert a regular string of numbers into ASCIII hexadecimal and store the hex in a string.

So I had something like

string random_string = "4000124273218347581"

and I wanted to convert it into a hexadecimal string in the form

string hex_string = "34303030313234323733323138333437353831"

This might seem like an oddly specific task but it's one I encountered and, when I tried to find out how to perform it, I couldn't find any answers online.

Anyway, I figured it out and created a class to make things tidier in my code.

In case anyone else needs to convert a regular string into a hexadecimal string I'll be posting an answer in a moment which will contain my solution.

(I'm fairly new to stackoverflow so I hope that doing this is okay)

=========================================

Turns out I can't answer my question myself within the first 8 hours of asking due to not having a high enough reputation.

So I'm sticking my answer here instead:

Okay, so here's my solution:

I created a class called StringToHex in the namespace

public class StringToHex
{
    private string localstring;
    private char[] char_array;
    private StringBuilder outputstring = new StringBuilder();
    private int value;

    public StringToHex(string text)
    {
        localstring = text;
    }

    public string ToAscii()
    {
        /* Convert text into an array of characters */
        char_array = localstring.ToCharArray();
        foreach (char letter in char_array)
        {
            /* Get the integral value of the character */
            value = Convert.ToInt32(letter);

            /* Convert the decimal value to a hexadecimal value in string form */
            string hex = String.Format("{0:X}", value);

            /* Append hexadecimal version of the char to the string outputstring*/
            outputstring.Append(Convert.ToString(hex));
        }
    return outputstring.ToString();
    }
}

And to use it you need to do something of the form:

/* Convert string to hexadecimal */
StringToHex an_instance_of_stringtohex = new StringToHex(string_to_convert);
string converted_string = an_instance_of_stringtohex.ToAscii();

If it's working properly, the converted string should be twice the length of the original string (due to hex using two bytes to represent each character).

Now, as someone's already pointed out, you can find an article doing something similar here:

http://www.c-sharpcorner.com/UploadFile/Joshy_geo/HexConverter10282006021521AM/HexConverter.aspx

But I didn't find it much help for my specific task and I'd like to think that my solution is more elegant ;)

Upvotes: 1

Views: 8487

Answers (3)

GeorgePotter
GeorgePotter

Reputation: 899

Okay, so here's my solution:

I created a class called StringToHex in the namespace

public class StringToHex
{
    private string localstring;
    private char[] char_array;
    private StringBuilder outputstring = new StringBuilder();
    private int value;

    public StringToHex(string text)
    {
        localstring = text;
    }

    public string ToAscii()
    {
        /* Convert text into an array of characters */
        char_array = localstring.ToCharArray();
        foreach (char letter in char_array)
        {
            /* Get the integral value of the character */
            value = Convert.ToInt32(letter);

            /* Convert the decimal value to a hexadecimal value in string form */
            string hex = String.Format("{0:X}", value);

            /* Append hexadecimal version of the char to the string outputstring*/
            outputstring.Append(Convert.ToString(hex));
        }
    return outputstring.ToString();
    }
}

And to use it you need to do something of the form:

/* Convert string to hexadecimal */
StringToHex an_instance_of_stringtohex = new StringToHex(string_to_convert);
string converted_string = an_instance_of_stringtohex.ToAscii();

If it's working properly, the converted string should be twice the length of the original string (due to hex using two bytes to represent each character).

Now, as someone's already pointed out, you can find an article doing something similar here:

http://www.c-sharpcorner.com/UploadFile/Joshy_geo/HexConverter10282006021521AM/HexConverter.aspx

But I didn't find it much help for my specific task and I'd like to think that my solution is more elegant ;)

Upvotes: -1

Guffa
Guffa

Reputation: 700152

This works as long as the character codes in the string is not greater than 255 (0xFF):

string hex_string =
  String.Concat(random_string.Select(c => ((int)c).ToString("x2")));

Note: This also works for character codes below 16 (0x10), e.g. it will produce the hex codes "0D0A" from the line break characters "\r\n", not "DA".

Upvotes: 7

Dor Cohen
Dor Cohen

Reputation: 17080

you need to read the following article -

http://www.c-sharpcorner.com/UploadFile/Joshy_geo/HexConverter10282006021521AM/HexConverter.aspx

the main function that converts 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;
}

see if this what you are looking for.

Upvotes: 2

Related Questions