1

Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa?

i have a List, i need to convert it to hex strings. i feel like the way i am converting is quiet long.

List<byte> TRIGGER_POL = Data.GetRange(23, 1);
byte[] TRIGGER_POL_temp = new byte[TRIGGER_POL.Count];
TRIGGER_POL_temp[0] = TRIGGER_POL[0];
string TRIGGER_POL_hx = BitConverter.ToString(TRIGGER_POL_temp, 0).Replace("-", string.Empty);

is there a faster, efficient way to do this?

Thanks..

Community
  • 1
  • 1
Liban
  • 641
  • 5
  • 19
  • 32
  • Don't know if it's faster, but generally when you want to convert a byte-array to a string you use Encoding..GetString. – Alxandr Jan 30 '13 at 03:43
  • So you want the whole array as 1 string or just the bytes to a list of strings (eg: byte(233) = "233") – sa_ddam213 Jan 30 '13 at 03:50
  • @sa_ddam213, i need to convert to list byte array to hex strings. sorry i forgot to mention before the conversion to hex strings. ex: `T[255 0] = 0xF0` – Liban Jan 30 '13 at 03:56

3 Answers3

3

There are losts of ways to do this but this one may work for you

 List<string> hexStrings = TRIGGER_POL.Select(b => BitConverter.ToString(new byte[]{b})).ToList();

or if you want just 1 string

string hex = BitConverter.ToString(TRIGGER_POL.ToArray());
sa_ddam213
  • 42,848
  • 7
  • 101
  • 110
  • the second conversion `TRIGGER_POL.ToArray()` works great and reduces number of lines.. thanks – Liban Jan 30 '13 at 04:18
2

My personal favorate way of doing this is a little known class buried deep within .NET SoapHexBinary

byte[] tmp1 = SoapHexBinary.Parse("DEADBEEF"); //tmp1 now equals the array {0xDE, 0xAD, 0xBE, 0xEF}
string tmp2 = new SoapHexBinary(tmp1).ToString(); //tmp2 now equals "DEADBEEF"
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
1

Try this:

public static string ConvertToHex(byte[] bytes)
{
    SoapHexBinary hexBin = new SoapHexBinary(bytes);
    return hexBin.ToString();
}
return ConvertToHex(TRIGGER_POL.ToArray());
Memoizer
  • 2,231
  • 1
  • 14
  • 14