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

系统。Byte []

而不是数值。

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


当前回答

我不经常把字节转换成十六进制所以我不知道有没有更好的方法,但这里有一种方法。

StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
    sb.Append(b.ToString("X2"));

string hexString = sb.ToString();

其他回答

我想我做了一个更快的字节数组到字符串转换器:

public static class HexTable
{
    private static readonly string[] table = BitConverter.ToString(Enumerable.Range(0, 256).Select(x => (byte)x).ToArray()).Split('-');

    public static string ToHexTable(byte[] value)
    {
        StringBuilder sb = new StringBuilder(2 * value.Length);

        for (int i = 0; i < value.Length; i++)
            sb.Append(table[value[i]]);

        return sb.ToString();
    }

并且测试设置:

static void Main(string[] args)
{
        const int TEST_COUNT = 10000;
        const int BUFFER_LENGTH = 100000;

        Random random = new Random();

        Stopwatch sw = new Stopwatch();
        Stopwatch sw2 = new Stopwatch();

        byte[] buffer = new byte[BUFFER_LENGTH];
        random.NextBytes(buffer);

        sw.Start();
        for (int j = 0; j < TEST_COUNT; j++)
            HexTable.ToHexTable(buffer);

        sw.Stop();

        sw2.Start();
        for (int j = 0; j < TEST_COUNT; j++)
            ToHexChar.ToHex(buffer);

        sw2.Stop();

        Console.WriteLine("Hex Table Elapsed Milliseconds: {0}", sw.ElapsedMilliseconds);
        Console.WriteLine("ToHex Elapsed Milliseconds: {0}", sw2.ElapsedMilliseconds);
    }

ToHexChar.ToHEx()方法是前面所示的ToHex()方法。

结果如下:

HexTable = 11808 ms ToHEx = 12168ms

它看起来可能没有太大的不同,但它仍然更快:)

非常快速的扩展方法(带反转):

public static class ExtensionMethods {
    public static string ToHex(this byte[] data) {
        return ToHex(data, "");
    }
    public static string ToHex(this byte[] data, string prefix) {
        char[] lookup = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        int i = 0, p = prefix.Length, l = data.Length;
        char[] c = new char[l * 2 + p];
        byte d;
        for(; i < p; ++i) c[i] = prefix[i];
        i = -1;
        --l;
        --p;
        while(i < l) {
            d = data[++i];
            c[++p] = lookup[d >> 4];
            c[++p] = lookup[d & 0xF];
        }
        return new string(c, 0, c.Length);
    }
    public static byte[] FromHex(this string str) {
        return FromHex(str, 0, 0, 0);
    }
    public static byte[] FromHex(this string str, int offset, int step) {
        return FromHex(str, offset, step, 0);
    }
    public static byte[] FromHex(this string str, int offset, int step, int tail) {
        byte[] b = new byte[(str.Length - offset - tail + step) / (2 + step)];
        byte c1, c2;
        int l = str.Length - tail;
        int s = step + 1;
        for(int y = 0, x = offset; x < l; ++y, x += s) {
            c1 = (byte)str[x];
            if(c1 > 0x60) c1 -= 0x57;
            else if(c1 > 0x40) c1 -= 0x37;
            else c1 -= 0x30;
            c2 = (byte)str[++x];
            if(c2 > 0x60) c2 -= 0x57;
            else if(c2 > 0x40) c2 -= 0x37;
            else c2 -= 0x30;
            b[y] = (byte)((c1 << 4) + c2);
        }
        return b;
    }
}

在上面的速度测试中击败所有其他人:

=== Long string test BitConvertReplace calculation Time Elapsed 2415 ms StringBuilder calculation Time Elapsed 5668 ms LinqConcat calculation Time Elapsed 11826 ms LinqJoin calculation Time Elapsed 9323 ms LinqAgg calculation Time Elapsed 7444 ms ToHexTable calculation Time Elapsed 1028 ms ToHexAcidzombie calculation Time Elapsed 1035 ms ToHexPatrick calculation Time Elapsed 814 ms ToHexKurt calculation Time Elapsed 1604 ms ByteArrayToHexString calculation Time Elapsed 1330 ms === Many string test BitConvertReplace calculation Time Elapsed 2238 ms StringBuilder calculation Time Elapsed 5393 ms LinqConcat calculation Time Elapsed 9043 ms LinqJoin calculation Time Elapsed 9131 ms LinqAgg calculation Time Elapsed 7324 ms ToHexTable calculation Time Elapsed 968 ms ToHexAcidzombie calculation Time Elapsed 969 ms ToHexPatrick calculation Time Elapsed 956 ms ToHexKurt calculation Time Elapsed 1547 ms ByteArrayToHexString calculation Time Elapsed 1277 ms

我不经常把字节转换成十六进制所以我不知道有没有更好的方法,但这里有一种方法。

StringBuilder sb = new StringBuilder();
foreach (byte b in myByteArray)
    sb.Append(b.ToString("X2"));

string hexString = sb.ToString();

下面是另一种方法:

public static string ByteArrayToHexString(byte[] Bytes)
{
    StringBuilder Result = new StringBuilder(Bytes.Length * 2);
    string HexAlphabet = "0123456789ABCDEF";

    foreach (byte B in Bytes)
    {
        Result.Append(HexAlphabet[(int)(B >> 4)]);
        Result.Append(HexAlphabet[(int)(B & 0xF)]);
    }

    return Result.ToString();
}

public static byte[] HexStringToByteArray(string Hex)
{
    byte[] Bytes = new byte[Hex.Length / 2];
    int[] HexValue = new int[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 
       0x06, 0x07, 0x08, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 
       0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };

    for (int x = 0, i = 0; i < Hex.Length; i += 2, x += 1)
    {
        Bytes[x] = (byte)(HexValue[Char.ToUpper(Hex[i + 0]) - '0'] << 4 |
                          HexValue[Char.ToUpper(Hex[i + 1]) - '0']);
    }

    return Bytes;
}

或者,你可以像这样预先构建翻译表,以获得更快的结果:

http://blogs.msdn.com/b/blambert/archive/2009/02/22/blambert-codesnip-fast-byte-array-to-hex-string-conversion.aspx

有一个内置的方法:

byte[] data = { 1, 2, 4, 8, 16, 32 };

string hex = BitConverter.ToString(data);

结果:01-02-04-08-10-20

如果你想要没有破折号,只需删除它们:

string hex = BitConverter.ToString(data).Replace("-", string.Empty);

结果:010204081020

如果你想要一个更紧凑的表示,你可以使用Base64:

string base64 = Convert.ToBase64String(data);

结果:AQIECBAg