views:

16160

answers:

5

As indicated in the answers, this is a duplicate of "How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?"


Hi,

Can we converting a hex string to a byte array using a built-in function in C# or I have to make a custom method for this?

+1  A: 

See this question.
Tomalak's answer:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
  bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}
InsDel
+12  A: 

Here's a nice fun LINQ example.

public static byte[] StringToByteArray(string hex) {
    return Enumerable.Range(0, hex.Length).
           Where(x => 0 == x % 2).
           Select(x => Convert.ToByte(hex.Substring(x, 2), 16)).
           ToArray();
}
JaredPar
A: 

Convert.ToByte in which package?

may
A: 

Compact:

public static string ByteArrayToString(byte[] ba) 
{
    // concat the bytes into one long string
    return ba.Aggregate(new StringBuilder(32),
                            (sb, b) => sb.Append(b.ToString("X2"))
                            ).ToString();
}

Or, a faster version...

public static string ByteArrayToString(byte[] ba)   
{   
   StringBuilder hex = new StringBuilder(ba.Length * 2);   

   for(int i=0; i < ga.Length; i++)       // <-- use for loop is faster than foreach   
       hex.Append(ba[i].ToString("X2"));   // <-- ToString is faster than AppendFormat   

   return hex.ToString();   
} 
Mark