从字节转换为十六进制字符串的内置函数

时间:2010-02-20 05:01:54

标签: c#

这是一个类似于this one here的问题。

是否有内置方法将字节数组转换为十六进制字符串?更具体地说,我正在寻找

的内置功能
    /// <summary>
    /// Convert bytes in a array Bytes to string in hexadecimal format
    /// </summary>
    /// <param name="Bytes">Bytes array</param>
    /// <param name="Length">Total byte to convert</param>
    /// <returns></returns>
    public static string ByteToHexString(byte[] Bytes, int Length)
    {
        Debug.Assert(Length <= Bytes.GetLength(0));
        StringBuilder hexstr = new StringBuilder();

        for (int i = 0; i < Length; i++)
        {
            hexstr.AppendFormat("{0,02:X}", Bytes[i]);
        }

        hexstr.Replace(' ', '0'); //padd empty space to zero

        return hexstr.ToString();
    }

1 个答案:

答案 0 :(得分:4)

使用BitConverter,参考:http://msdn.microsoft.com/en-us/library/bb311038.aspx

byte[] vals = { 0x01, 0xAA, 0xB1, 0xDC, 0x10, 0xDD };

var str = BitConverter.ToString(vals).Replace("-", "");
Console.WriteLine(str);

/*Output:
  01AAB1DC10DD
 */