HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Conversion of hexadecimal string to string

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
conversionstringhexadecimal

Problem

Given a C# string which is a set of hexadecimal numbers such as:

string HexString = "202048656c6c6f20576f726c64313233212020";


Where those hexadecimal numbers represent the ASCII text:

"  Hello World123!  "


I need to convert the HexString to a String and I have the following code which works, but looks so excessive!

string HexStringToString(string HexString) {
    string stringValue = "";
    for (int i = 0; i < HexString.Length / 2; i++) {
        string hexChar = HexString.Substring(i * 2, 2);
        int hexValue = Convert.ToInt32(hexChar, 16);
        stringValue += Char.ConvertFromUtf32(hexValue);
    }
    return stringValue;
}


Am I missing some elegant method?

Solution

I don't think there is a built-in method. Yours is pretty good but we could make some improvements:

  • Parameters should be camelCase => hexString.



  • You should favour StringBuilder when building up strings.



  • You should step through the string in increments of 2 to cut down on the maths.



  • You should validate the argument.



  • You should prefer var when the type is obvious.



Result of those points:

string HexStringToString(string hexString) 
{
    if (hexString == null || (hexString.Length & 1) == 1) 
    {
        throw new ArgumentException();
    }
    var sb = new StringBuilder();
    for (var i = 0; i < hexString.Length; i += 2) {
        var hexChar = hexString.Substring(i, 2);
        sb.Append((char)Convert.ToByte(hexChar, 16));
    }
    return sb.ToString();
}

Code Snippets

string HexStringToString(string hexString) 
{
    if (hexString == null || (hexString.Length & 1) == 1) 
    {
        throw new ArgumentException();
    }
    var sb = new StringBuilder();
    for (var i = 0; i < hexString.Length; i += 2) {
        var hexChar = hexString.Substring(i, 2);
        sb.Append((char)Convert.ToByte(hexChar, 16));
    }
    return sb.ToString();
}

Context

StackExchange Code Review Q#97950, answer score: 12

Revisions (0)

No revisions yet.