Convert from string ascii to string Hex

This seems the job for an extension method

void Main()
{
    string test = "ABCD1234";
    string result = test.ToHex();
}

public static class StringExtensions
{
    public static string ToHex(this string input)
    {
        StringBuilder sb = new StringBuilder();
        foreach(char c in input)
            sb.AppendFormat("0x{0:X2} ", (int)c);
        return sb.ToString().Trim();
    }
}

A few tips.
Do not use string concatenation. Strings are immutable and thus every time you concatenate a string a new one is created. (Pressure on memory usage and fragmentation) A StringBuilder is generally more efficient for this case.

Strings are array of characters and using a foreach on a string already gives access to the character array

These common codes are well suited for an extension method included in a utility library always available for your projects (code reuse)


string str = "1234";
char[] charValues = str.ToCharArray();
string hexOutput="";
foreach (char _eachChar in charValues )
{
    // Get the integral value of the character.
    int value = Convert.ToInt32(_eachChar);
    // Convert the decimal value to a hexadecimal value in string form.
    hexOutput += String.Format("{0:X}", value);
    // to make output as your eg 
    //  hexOutput +=" "+ String.Format("{0:X}", value);

}

    //here is the HEX hexOutput 
    //use hexOutput 

Tags:

C#

Ascii

Hex

String