views:

8402

answers:

4
+2  Q: 

Hex To String C#

Hello,

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(example 00-50-25-40-A5-FF). I tried most function 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(example 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.

Thanks.

+2  A: 

Why not just remove the dashes?

1800 INFORMATION
+1  A: 
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}

Dead account
+1  A: 

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[])

Will Dean
+8  A: 

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;
}
Marc Gravell
// GatewayServer...have we been Copy+Pasting?
Dead account
@Ian - huh? That is the value of "s"...
Marc Gravell
@Marc,Thanks! @lan,That's the byte array I gave in my question,Marc is more thank helpful for checking it as string. :)
John
@Marc, yeah yeah.. I noticed that.. erm.. (hides under desk)
Dead account
@Marc,Encoding.ASCII has parameter char[].How to convert data into char[]?
John
@Marc,I did it in one line only. :) name = System.Text.Encoding.ASCII.GetString(data, 8, (int)BitConverter.ToUInt16(data, 6));
John
Which method on Encoding.Ascii? What data?
Marc Gravell