1

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 ;)

8
  • How does the "hexadecimal string" relate to the original? What rules? Commented Apr 4, 2012 at 13:30
  • 2
    put a 3 in front of every char :) Commented Apr 4, 2012 at 13:32
  • @HenkHolterman - Yeah, I did figure it out, but I wanted the OP to give more thought to how the question was framed. Commented Apr 4, 2012 at 13:32
  • 1
    It is OK to post a question and answer it yourself but a) check for dupes thoroughly and b) make it a (precise) question. Commented Apr 4, 2012 at 13:34
  • @L.B - If all characters are indeed numerals and the wanted hex encoding is ASCII, that would work well :) Commented Apr 4, 2012 at 13:35

3 Answers 3

7

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".

Sign up to request clarification or add additional context in comments.

Comments

2

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.

3 Comments

Please include the key pieces of information from that resource in your answer.
Yeah, I did read that article but I didn't find it that easy to understand to be honest - and that motivated me to post this question/answer in order to provide an alternative solution :)
That's method doesn't convert characters into hex format, it converts hex format into characters.
-1

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 ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.