Converting from hex to string
Asked Answered
R

8

45

I need to check for a string located inside a packet that I receive as byte array. If I use BitConverter.ToString(), I get the bytes as string with dashes (f.e.: 00-50-25-40-A5-FF).
I tried most functions I found after a quick googling, but most of them have input parameter type string and if I call them with the string with dashes, It throws an exception.

I need a function that turns hex(as string or as byte) into the string that represents the hexadecimal value(f.e.: 0x31 = 1). If the input parameter is string, the function should recognize dashes(example "47-61-74-65-77-61-79-53-65-72-76-65-72"), because BitConverter doesn't convert correctly.

Refresher answered 7/4, 2009 at 9:45 Comment(2)
Why not just remove the dashes?Last
I found a good method at Code Review: codereview.stackexchange.com/questions/97950/…Udo
P
94

Like so?

static void Main()
{
    byte[] data = FromHex("47-61-74-65-77-61-79-53-65-72-76-65-72");
    string s = Encoding.ASCII.GetString(data); // GatewayServer
}
public static byte[] FromHex(string hex)
{
    hex = hex.Replace("-", "");
    byte[] raw = new byte[hex.Length / 2];
    for (int i = 0; i < raw.Length; i++)
    {
        raw[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
    }
    return raw;
}
Planet answered 7/4, 2009 at 10:1 Comment(5)
@Marc,Thanks! @lan,That's the byte array I gave in my question,Marc is more thank helpful for checking it as string. :)Refresher
@Marc, yeah yeah.. I noticed that.. erm.. (hides under desk)Mackenzie
@Marc,Encoding.ASCII has parameter char[].How to convert data into char[]?Refresher
@Marc,I did it in one line only. :) name = System.Text.Encoding.ASCII.GetString(data, 8, (int)BitConverter.ToUInt16(data, 6));Refresher
Which method on Encoding.Ascii? What data?Planet
I
17

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}
Ibiza answered 8/12, 2014 at 17:23 Comment(2)
This doesn't seem to work. Using Windows 8.1, Visual C# 2010 Express.Dunbarton
@ akinuri - You probably want return Encoding.UTF8.GetString(bytes); depending on how it was encodedNika
M
13
string str = "47-61-74-65-77-61-79-53-65-72-76-65-72";
string[] parts = str.Split('-');

foreach (string val in parts)
{ 
    int x;
    if (int.TryParse(val, out x))
    {
         Console.Write(string.Format("{0:x2} ", x);
    }
}
Console.WriteLine();

You can split the string at the -
Convert the text to ints (int.TryParse)
Output the int as a hex string {0:x2}

Mackenzie answered 7/4, 2009 at 9:58 Comment(0)
H
2
 string hexString = "8E2";
 int num = Int32.Parse(hexString, System.Globalization.NumberStyles.HexNumber);
 Console.WriteLine(num);
 //Output: 2274

From https://msdn.microsoft.com/en-us/library/bb311038.aspx

Hekker answered 3/1, 2017 at 4:20 Comment(0)
V
1

Your reference to "0x31 = 1" makes me think you're actually trying to convert ASCII values to strings - in which case you should be using something like Encoding.ASCII.GetString(Byte[])

Valtin answered 7/4, 2009 at 9:59 Comment(0)
W
1

If you need the result as byte array, you should pass it directly without changing it to a string, then change it back to bytes. In your example the (f.e.: 0x31 = 1) is the ASCII codes. In that case to convert a string (of hex values) to ASCII values use: Encoding.ASCII.GetString(byte[])

        byte[] data = new byte[] { 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x30 };
        string ascii=Encoding.ASCII.GetString(data);
        Console.WriteLine(ascii);

The console will display: 1234567890

Weichsel answered 25/7, 2016 at 14:22 Comment(0)
C
0

My Net 5 solution that also handles null characters at the end:

hex = ConvertFromHex( hex.AsSpan(), Encoding.Default );

static string ConvertFromHex( ReadOnlySpan<char> hexString, Encoding encoding )
{
    int realLength = 0;
    for ( int i = hexString.Length - 2; i >= 0; i -= 2 )
    {
        byte b = byte.Parse( hexString.Slice( i, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
        if ( b != 0 ) //not NULL character
        {
            realLength = i + 2;
            break;
        }
    }
    
    var bytes = new byte[realLength / 2];
    for ( var i = 0; i < bytes.Length; i++ )
    {
        bytes[i] = byte.Parse( hexString.Slice( i * 2, 2 ), NumberStyles.HexNumber, CultureInfo.InvariantCulture );
    }

    return encoding.GetString( bytes );
}
Crackdown answered 23/1, 2021 at 2:30 Comment(0)
R
0

One-liners:

    var input = "Hallo Hélène and Mr. Hörst";
    var ConvertStringToHexString = (string input) => String.Join("", Encoding.UTF8.GetBytes(input).Select(b => $"{b:X2}"));
    var ConvertHexToString = (string hexInput) => Encoding.UTF8.GetString(Enumerable.Range(0, hexInput.Length / 2).Select(_ => Convert.ToByte(hexInput.Substring(_ * 2, 2), 16)).ToArray());
    Assert.AreEqual(input, ConvertHexToString(ConvertStringToHexString(input)));
Riehl answered 16/9, 2022 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.