如何将字节[]转换为字符串?每次我尝试,我都

系统。Byte []

而不是数值。

另外,我如何得到十六进制而不是小数的值?


当前回答

private static string GuidToRaw(Guid guid)
{
    byte[] bytes = guid.ToByteArray();

    int сharCount = bytes.Length * 2;
    char[] chars = new char[сharCount];

    int index = 0;
    for (int i = 0; i < сharCount; i += 2)
    {
        byte b = bytes[index++];
        chars[i] = GetHexValue((int)(b / 16));
        chars[i + 1] = GetHexValue((int)(b % 16));
    }
    return new string(chars, 0, chars.Length);
}

private static char GetHexValue(int i)
{
    return (char)(i < 10 ? i + 48 : i + 55);
}

其他回答

这里没人提到你为什么会有"系统"字节[]"字符串,而不是值,所以我将。

当一个对象隐式转换为String类型时,程序将默认使用该对象的公共String ToString()方法,该方法从System继承而来。对象:

public virtual string ToString()
{
    return this.GetType().ToString();
}

如果你发现你经常进行这种转换,你可以简单地创建一个包装器类,并像这样重写这个方法:

public override string ToString()
{
    // do the processing here
    // return the nicely formatted string
}

现在每次打印这个包装器对象时,你将得到你自己的值,而不是this. gettype (). tostring()的值。

我不确定你是否需要这样做的性能,但这里是最快的方法转换字节[]到十六进制字符串,我能想到:

static readonly char[] hexchar = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
public static string HexStr(byte[] data, int offset, int len, bool space = false)
{
    int i = 0, k = 2;
    if (space) k++;
    var c = new char[len * k];
    while (i < len)
    {
        byte d = data[offset + i];
        c[i * k] = hexchar[d / 0x10];
        c[i * k + 1] = hexchar[d % 0x10];
        if (space && i < len - 1) c[i * k + 2] = ' ';
        i++;
    }
    return new string(c, 0, c.Length);
}

再向这个堆中添加一个答案,有一个System.Runtime.Remoting.Metadata.W3cXsd2001。SoapHexBinary类,我已经使用它可以转换字节和十六进制:

string hex = new SoapHexBinary(bytes).ToString();
byte[] bytes = SoapHexBinary.Parse(hex).Value;

不确定它与其他实现(基准)相比如何,但在我看来,它非常简单——特别是从十六进制转换回字节。

你把LINQ和字符串方法结合起来:

string hex = string.Join("",
  bin.Select(
    bin => bin.ToString("X2")
      ).ToArray());

你必须知道以字节表示的字符串的编码,但是你可以说System.Text.UTF8Encoding.GetString(字节)或System.Text.ASCIIEncoding.GetString(字节)。(我是根据记忆做的,所以API可能不完全正确,但它非常接近。)

第二个问题的答案,请看这个问题。