如何将字节数组转换为十六进制字符串,反之亦然?

有帮助吗?

解决方案

或者:

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

或:

public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-","");
}

还有更多的变种,例如这里

反向转换将如下:

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;
}

使用Substring是与Convert.ToByte结合使用的最佳选择。有关详细信息,请参阅此答案。如果您需要更好的性能,则必须避免SubString才能删除<=>。

其他提示

绩效分析

笔记:截至 2015 年 8 月 20 日的新领导者。

我通过一些粗略的方法运行了各种转换方法 Stopwatch 性能测试,使用随机句子运行(n=61,1000 次迭代)和使用古腾堡项目文本运行(n=1,238,957,150 次迭代)。以下是结果,大致从最快到最慢。所有测量值均以刻度为单位 (10,000 个刻度 = 1 毫秒) 并将所有相关注释与 [最慢] 进行比较 StringBuilder 执行。对于所使用的代码,请参见下文或 测试框架仓库 我现在在其中维护运行此代码的代码。

免责声明

警告:不要依赖这些统计数据来获得任何具体的信息;它们只是样本数据的样本运行。如果您确实需要一流的性能,请在代表您的生产需求的环境中测试这些方法,并使用代表您将使用的数据。

结果

查找表已经领先于字节操作。基本上,有某种形式的预计算任何给定的半字节或字节的十六进制形式。然后,当您浏览数据时,您只需查找下一部分即可查看它是什么十六进制字符串。然后该值以某种方式添加到结果字符串输出中。长期以来,字节操作(对于某些开发人员来说可能更难阅读)是性能最好的方法。

您最好的选择仍然是找到一些代表性数据并在类似生产的环境中进行尝试。如果您有不同的内存限制,您可能更喜欢分配较少的方法,而不是速度更快但消耗更多内存的方法。

测试代码

请随意使用我使用的测试代码。此处包含一个版本,但请随意克隆 回购协议 并添加您自己的方法。如果您发现任何有趣的内容或想要帮助改进其使用的测试框架,请提交拉取请求。

  1. 添加新的静态方法(Func<byte[], string>)到/Tests/ConvertByteArrayToHexString/Test.cs。
  2. 将该方法的名称添加到 TestCandidates 返回同一个类中的值。
  3. 通过切换注释,确保您正在运行所需的输入版本、句子或文本 GenerateTestInput 在同一个班级。
  4. F5 并等待输出(/bin 文件夹中还会生成 HTML 转储)。
static string ByteArrayToHexStringViaStringJoinArrayConvertAll(byte[] bytes) {
    return string.Join(string.Empty, Array.ConvertAll(bytes, b => b.ToString("X2")));
}
static string ByteArrayToHexStringViaStringConcatArrayConvertAll(byte[] bytes) {
    return string.Concat(Array.ConvertAll(bytes, b => b.ToString("X2")));
}
static string ByteArrayToHexStringViaBitConverter(byte[] bytes) {
    string hex = BitConverter.ToString(bytes);
    return hex.Replace("-", "");
}
static string ByteArrayToHexStringViaStringBuilderAggregateByteToString(byte[] bytes) {
    return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.Append(b.ToString("X2"))).ToString();
}
static string ByteArrayToHexStringViaStringBuilderForEachByteToString(byte[] bytes) {
    StringBuilder hex = new StringBuilder(bytes.Length * 2);
    foreach (byte b in bytes)
        hex.Append(b.ToString("X2"));
    return hex.ToString();
}
static string ByteArrayToHexStringViaStringBuilderAggregateAppendFormat(byte[] bytes) {
    return bytes.Aggregate(new StringBuilder(bytes.Length * 2), (sb, b) => sb.AppendFormat("{0:X2}", b)).ToString();
}
static string ByteArrayToHexStringViaStringBuilderForEachAppendFormat(byte[] bytes) {
    StringBuilder hex = new StringBuilder(bytes.Length * 2);
    foreach (byte b in bytes)
        hex.AppendFormat("{0:X2}", b);
    return hex.ToString();
}
static string ByteArrayToHexViaByteManipulation(byte[] bytes) {
    char[] c = new char[bytes.Length * 2];
    byte b;
    for (int i = 0; i < bytes.Length; i++) {
        b = ((byte)(bytes[i] >> 4));
        c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
        b = ((byte)(bytes[i] & 0xF));
        c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
    }
    return new string(c);
}
static string ByteArrayToHexViaByteManipulation2(byte[] bytes) {
    char[] c = new char[bytes.Length * 2];
    int b;
    for (int i = 0; i < bytes.Length; i++) {
        b = bytes[i] >> 4;
        c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7));
        b = bytes[i] & 0xF;
        c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7));
    }
    return new string(c);
}
static string ByteArrayToHexViaSoapHexBinary(byte[] bytes) {
    SoapHexBinary soapHexBinary = new SoapHexBinary(bytes);
    return soapHexBinary.ToString();
}
static string ByteArrayToHexViaLookupAndShift(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();
}
static readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_Lookup32, GCHandleType.Pinned).AddrOfPinnedObject();
static string ByteArrayToHexViaLookup32UnsafeDirect(byte[] bytes) {
    var lookupP = _lookup32UnsafeP;
    var result = new string((char)0, bytes.Length * 2);
    fixed (byte* bytesP = bytes)
    fixed (char* resultP = result) {
        uint* resultP2 = (uint*)resultP;
        for (int i = 0; i < bytes.Length; i++) {
            resultP2[i] = lookupP[bytesP[i]];
        }
    }
    return result;
}
static uint[] _Lookup32 = Enumerable.Range(0, 255).Select(i => {
    string s = i.ToString("X2");
    return ((uint)s[0]) + ((uint)s[1] << 16);
}).ToArray();
static string ByteArrayToHexViaLookupPerByte(byte[] bytes) {
    var result = new char[bytes.Length * 2];
    for (int i = 0; i < bytes.Length; i++)
    {
        var val = _Lookup32[bytes[i]];
        result[2*i] = (char)val;
        result[2*i + 1] = (char) (val >> 16);
    }
    return new string(result);
}
static string ByteArrayToHexViaLookup(byte[] bytes) {
    string[] hexStringTable = new string[] {
        "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F",
        "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F",
        "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F",
        "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F",
        "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F",
        "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F",
        "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F",
        "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F",
        "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F",
        "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
        "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF",
        "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF",
        "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF",
        "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF",
        "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF",
        "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF",
    };
    StringBuilder result = new StringBuilder(bytes.Length * 2);
    foreach (byte b in bytes) {
        result.Append(hexStringTable[b]);
    }
    return result.ToString();
}

更新 (2010-01-13)

添加了瓦利德对分析的回答。蛮快。

更新 (2011-10-05)

添加 string.Concat Array.ConvertAll 完整性变体(需要 .NET 4.0)。与 string.Join 版本。

更新 (2012-02-05)

测试存储库包含更多变体,例如 StringBuilder.Append(b.ToString("X2")). 。没有人对结果有任何影响。 foreach{IEnumerable}.Aggregate, ,例如,但是 BitConverter 仍然获胜。

更新 (2012-04-03)

添加了麦克罗夫特的 SoapHexBinary 分析答案,占据第三位。

更新(2013-01-15)

添加了 CodesInChaos 的字节操作答案,该答案占据了第一名(在大文本块上大幅领先)。

更新 (2013-05-23)

添加了 Nathan Moinvaziri 的查找答案和 Brian Lambert 博客中的变体。两者都相当快,但在我使用的测试机(AMD Phenom 9750)上并不领先。

更新 (2014-07-31)

添加了 @CodesInChaos 的新的基于字节的查找答案。它似乎在句子测试和全文测试中都处于领先地位。

更新 (2015-08-20)

添加 呼吸器的 优化和 unsafe 对此的变体 答案的回购协议. 。如果您想玩不安全的游戏,那么无论是在短字符串还是大文本上,您都可以获得比之前任何顶级获胜者更大的性能提升。

在编写加密代码时,通常会避免依赖于数据的分支和表查找,以确保运行时不依赖于数据,因为依赖于数据的时序可能会导致旁道攻击。

它也相当快。

static string ByteToHexBitFiddle(byte[] bytes)
{
    char[] c = new char[bytes.Length * 2];
    int b;
    for (int i = 0; i < bytes.Length; i++) {
        b = bytes[i] >> 4;
        c[i * 2] = (char)(55 + b + (((b-10)>>31)&-7));
        b = bytes[i] & 0xF;
        c[i * 2 + 1] = (char)(55 + b + (((b-10)>>31)&-7));
    }
    return new string(c);
}

Ph'nglui mglw'nafh 克苏鲁 R'lyeh wgah'nagl fhtagn


进入这里的人请放弃所有希望

对奇怪的摆弄的解释:

  1. bytes[i] >> 4 提取一个字节的高半字节
    bytes[i] & 0xF 提取字节的低半字节
  2. b - 10
    < 0 为了价值观 b < 10, ,这将成为十进制数字
    >= 0 为了价值观 b > 10, ,这将成为一封来自 AF.
  3. 使用 i >> 31 由于符号扩展,在有符号的 32 位整数上提取符号。这将是 -1 为了 i < 00 为了 i >= 0.
  4. 结合 2) 和 3),表明 (b-10)>>310 对于字母和 -1 对于数字。
  5. 查看字母的大小写,最后一个被加数变为 0, , 和 b 范围是 10 到 15。我们想将它映射到 A(65)到 F(70),这意味着添加 55 ('A'-10).
  6. 看看数字的情况,我们想要调整最后一个被加数,以便它映射 b 从范围 0 到 9 到范围 0(48)到 9(57)。这意味着它需要变成-7('0' - 55).
    现在我们可以乘以 7。但由于 -1 表示所有位均为 1,因此我们可以使用 & -7 自从 (0 & -7) == 0(-1 & -7) == -7.

一些进一步的考虑:

  • 我没有使用第二个循环变量来索引 c, ,因为测量表明计算它 i 更便宜。
  • 准确使用 i < bytes.Length 作为循环的上限允许 JITter 消除边界检查 bytes[i], ,所以我选择了那个变体。
  • 制作 b int 允许与字节进行不必要的转换。

如果你想要比BitConverter更灵活,但又不想要那些笨重的20世纪90年代风格的显式循环,那么你可以这样做:

String.Join(String.Empty, Array.ConvertAll(bytes, x => x.ToString("X2")));

或者,如果您使用的是.NET 4.0:

String.Concat(Array.ConvertAll(bytes, x => x.ToString("X2")));

(后者来自对原帖的评论。)

另一种基于查找表的方法。这个每个字节只使用一个查找表,而不是每个半字节的查找表。

private static readonly uint[] _lookup32 = CreateLookup32();

private static uint[] CreateLookup32()
{
    var result = new uint[256];
    for (int i = 0; i < 256; i++)
    {
        string s=i.ToString("X2");
        result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
    }
    return result;
}

private static string ByteArrayToHexViaLookup32(byte[] bytes)
{
    var lookup32 = _lookup32;
    var result = new char[bytes.Length * 2];
    for (int i = 0; i < bytes.Length; i++)
    {
        var val = lookup32[bytes[i]];
        result[2*i] = (char)val;
        result[2*i + 1] = (char) (val >> 16);
    }
    return new string(result);
}

我还在查找表中使用ushortstruct{char X1, X2}struct{byte X1, X2}测试了它的变体。

根据编译目标(x86,X64),它们具有大致相同的性能或略慢于此变体。


为了获得更高的性能,它的unsafe兄弟:

private static readonly uint[] _lookup32Unsafe = CreateLookup32Unsafe();
private static readonly uint* _lookup32UnsafeP = (uint*)GCHandle.Alloc(_lookup32Unsafe,GCHandleType.Pinned).AddrOfPinnedObject();

private static uint[] CreateLookup32Unsafe()
{
    var result = new uint[256];
    for (int i = 0; i < 256; i++)
    {
        string s=i.ToString("X2");
        if(BitConverter.IsLittleEndian)
            result[i] = ((uint)s[0]) + ((uint)s[1] << 16);
        else
            result[i] = ((uint)s[1]) + ((uint)s[0] << 16);
    }
    return result;
}

public static string ByteArrayToHexViaLookup32Unsafe(byte[] bytes)
{
    var lookupP = _lookup32UnsafeP;
    var result = new char[bytes.Length * 2];
    fixed(byte* bytesP = bytes)
    fixed (char* resultP = result)
    {
        uint* resultP2 = (uint*)resultP;
        for (int i = 0; i < bytes.Length; i++)
        {
            resultP2[i] = lookupP[bytesP[i]];
        }
    }
    return new string(result);
}

或者如果你认为直接写入字符串是可以接受的:

public static string ByteArrayToHexViaLookup32UnsafeDirect(byte[] bytes)
{
    var lookupP = _lookup32UnsafeP;
    var result = new string((char)0, bytes.Length * 2);
    fixed (byte* bytesP = bytes)
    fixed (char* resultP = result)
    {
        uint* resultP2 = (uint*)resultP;
        for (int i = 0; i < bytes.Length; i++)
        {
            resultP2[i] = lookupP[bytesP[i]];
        }
    }
    return result;
}

我今天刚遇到同样的问题,我遇到了这段代码:

private static string ByteArrayToHex(byte[] barray)
{
    char[] c = new char[barray.Length * 2];
    byte b;
    for (int i = 0; i < barray.Length; ++i)
    {
        b = ((byte)(barray[i] >> 4));
        c[i * 2] = (char)(b > 9 ? b + 0x37 : b + 0x30);
        b = ((byte)(barray[i] & 0xF));
        c[i * 2 + 1] = (char)(b > 9 ? b + 0x37 : b + 0x30);
    }
    return new string(c);
}

来源:论坛帖子 byte [] Array to Hex String (参见PZahra的帖子)。我稍微修改了代码以删除0x前缀。

我对代码进行了一些性能测试,它比使用BitConverter.ToString()快了近8倍(根据patridge的帖子,速度最快)。

这个问题也可以使用查找表来解决。这将需要少量的静态存储器用于编码器和解码器。然而,这种方法会很快:

  • 编码器表512字节或1024个字节(如果需要上下情况,大小是两倍)
  • 解码器表256字节或64 KIB(单个炭架或双char查找)

我的解决方案使用 1024 字节用于编码表,使用 256 字节用于解码。

解码

private static readonly byte[] LookupTable = new byte[] {
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};

private static byte Lookup(char c)
{
  var b = LookupTable[c];
  if (b == 255)
    throw new IOException("Expected a hex character, got " + c);
  return b;
}

public static byte ToByte(char[] chars, int offset)
{
  return (byte)(Lookup(chars[offset]) << 4 | Lookup(chars[offset + 1]));
}

编码

private static readonly char[][] LookupTableUpper;
private static readonly char[][] LookupTableLower;

static Hex()
{
  LookupTableLower = new char[256][];
  LookupTableUpper = new char[256][];
  for (var i = 0; i < 256; i++)
  {
    LookupTableLower[i] = i.ToString("x2").ToCharArray();
    LookupTableUpper[i] = i.ToString("X2").ToCharArray();
  }
}

public static char[] ToCharLower(byte[] b, int bOffset)
{
  return LookupTableLower[b[bOffset]];
}

public static char[] ToCharUpper(byte[] b, int bOffset)
{
  return LookupTableUpper[b[bOffset]];
}

比较

StringBuilderToStringFromBytes:   106148
BitConverterToStringFromBytes:     15783
ArrayConvertAllToStringFromBytes:  54290
ByteManipulationToCharArray:        8444
TableBasedToCharArray:              5651 *

* 这个解决方案

笔记

在解码期间,可能会发生 IOException 和 IndexOutOfRangeException(如果字符的值太高 > 256)。应该实现对流或数组进行解码/编码的方法,这只是概念证明。

这是一个答案 修订版4托马拉克的热门答案 (以及后续编辑)。

我将证明此编辑是错误的,并解释为什么可以恢复它。在此过程中,您可能会了解一些内部原理的一两件事,并看到另一个示例,了解过早优化的真正含义以及它如何对您造成影响。

长话短说: 只需使用 Convert.ToByteString.Substring 如果你很着急(下面的“原始代码”),如果你不想重新实现,这是最好的组合 Convert.ToByte. 。使用不使用的更高级的东西(参见其他答案) Convert.ToByte 如果你 需要 表现。做 不是 使用除 String.Substring 结合 Convert.ToByte, ,除非有人在这个答案的评论中对此有一些有趣的说法。

警告: 这个答案可能会过时 如果 A Convert.ToByte(char[], Int32) 重载是在框架中实现的。这不太可能很快发生。

一般来说,我不太喜欢说“不要过早优化”,因为没有人知道什么时候是“过早优化”。在决定是否优化时,您唯一必须考虑的是:“我有时间和资源来正确研究优化方法吗?”。如果你不这样做,那就太早了,等到你的项目更成熟或者你需要性能时(如果确实有需要,那么你会 制作 时间)。与此同时,做一些可能有效的最简单的事情。

原始代码:

    public static byte[] HexadecimalStringToByteArray_Original(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        for (var i = 0; i < outputLength; i++)
            output[i] = Convert.ToByte(input.Substring(i * 2, 2), 16);
        return output;
    }

修订版 4:

    public static byte[] HexadecimalStringToByteArray_Rev4(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        using (var sr = new StringReader(input))
        {
            for (var i = 0; i < outputLength; i++)
                output[i] = Convert.ToByte(new string(new char[2] { (char)sr.Read(), (char)sr.Read() }), 16);
        }
        return output;
    }

此次修订避免了 String.Substring 并使用一个 StringReader 反而。给出的原因是:

编辑:您可以通过使用单个通行证解析器来提高长字符串的性能,例如:

嗯,看着 参考代码为 String.Substring, ,显然已经是“单程”了;为什么不应该这样呢?它在字节级别运行,而不是在代理对上运行。

然而,它确实分配了一个新字符串,但是您需要分配一个来传递给 Convert.ToByte 反正。此外,修订版中提供的解决方案在每次迭代时分配另一个对象(两个字符数组);您可以安全地将分配放在循环之外并重用数组以避免这种情况。

    public static byte[] HexadecimalStringToByteArray(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        using (var sr = new StringReader(input))
        {
            for (var i = 0; i < outputLength; i++)
            {
                numeral[0] = (char)sr.Read();
                numeral[1] = (char)sr.Read();
                output[i] = Convert.ToByte(new string(numeral), 16);
            }
        }
        return output;
    }

每个十六进制 numeral 使用两个数字(符号)表示单个八位位组。

但是,为什么打电话 StringReader.Read 两次?只需调用它的第二个重载并要求它一次读取双字符数组中的两个字符即可;并将调用次数减少两次。

    public static byte[] HexadecimalStringToByteArray(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        using (var sr = new StringReader(input))
        {
            for (var i = 0; i < outputLength; i++)
            {
                var read = sr.Read(numeral, 0, 2);
                Debug.Assert(read == 2);
                output[i] = Convert.ToByte(new string(numeral), 16);
            }
        }
        return output;
    }

您剩下的是一个字符串读取器,其唯一添加的“值”是并行索引(内部 _pos)你可以自己声明(如 j 例如),冗余长度变量(内部 _length),以及对输入字符串的冗余引用(内部 _s)。换句话说,它是没有用的。

如果你想知道如何 Read “读”,只需看一下 代码, ,它所做的就是调用 String.CopyTo 在输入字符串上。其余的只是簿记开销,用于维护我们不需要的值。

因此,已经删除字符串读取器,然后调用 CopyTo 你自己;它更简单、更清晰、更高效。

    public static byte[] HexadecimalStringToByteArray(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        for (int i = 0, j = 0; i < outputLength; i++, j += 2)
        {
            input.CopyTo(j, numeral, 0, 2);
            output[i] = Convert.ToByte(new string(numeral), 16);
        }
        return output;
    }

你真的需要一个 j 索引以两个平行的步长递增 i?当然不是,乘以就可以了 i 两倍(编译器应该能够优化为加法)。

    public static byte[] HexadecimalStringToByteArray_BestEffort(string input)
    {
        var outputLength = input.Length / 2;
        var output = new byte[outputLength];
        var numeral = new char[2];
        for (int i = 0; i < outputLength; i++)
        {
            input.CopyTo(i * 2, numeral, 0, 2);
            output[i] = Convert.ToByte(new string(numeral), 16);
        }
        return output;
    }

现在的解决方案是什么样的?和一开始一样,只是不使用 String.Substring 要分配字符串并将数据复制到其中,您将使用一个中间数组,将十六进制数字复制到其中,然后自己分配字符串并复制数据 再次 从数组到字符串(当您在字符串构造函数中传递它时)。如果字符串已经在实习池中,则第二个副本可能会被优化,但随后 String.Substring 在这些情况下也可以避免它。

事实上,如果你看一下 String.Substring 再次,您会看到它使用了一些有关如何构造字符串的低级内部知识来比通常更快地分配字符串,并且它内联了与 CopyTo 直接在那里以避免调用开销。

String.Substring

  • 最坏的情况下:一种快速分配,一种快速复制。
  • 最好的情况:没有分配,没有复制。

手动方法

  • 最坏的情况下:两种正常分配,一种正常复制,一种快速复制。
  • 最好的情况:一份正常分配,一份正常副本。

结论? 如果你想使用 Convert.ToByte(String, Int32) (因为你不想自己重新实现该功能),似乎没有办法击败 String.Substring;你所做的就是原地打转,重新发明轮子(仅适用于次优材料)。

请注意,使用 Convert.ToByteString.Substring 如果您不需要极端的性能,这是一个完全有效的选择。记住:仅当您有时间和资源来研究替代方案如何正常工作时,才选择替代方案。

如果有一个 Convert.ToByte(char[], Int32), ,事情当然会有所不同(可以按照我上面描述的方式进行操作并完全避免 String).

我怀疑那些通过“避免 String.Substring” 也避免 Convert.ToByte(String, Int32), ,如果您无论如何都需要性能,那么您确实应该这样做。查看无数其他答案,以发现所有不同的方法来做到这一点。

免责声明:我还没有反编译最新版本的框架来验证参考源是否是最新的,我想是的。

现在,这一切听起来都不错,也很合乎逻辑,如果您已经做到了这一点,希望它甚至是显而易见的。但这是真的吗?

Intel(R) Core(TM) i7-3720QM CPU @ 2.60GHz
    Cores: 8
    Current Clock Speed: 2600
    Max Clock Speed: 2600
--------------------
Parsing hexadecimal string into an array of bytes
--------------------
HexadecimalStringToByteArray_Original: 7,777.09 average ticks (over 10000 runs), 1.2X
HexadecimalStringToByteArray_BestEffort: 8,550.82 average ticks (over 10000 runs), 1.1X
HexadecimalStringToByteArray_Rev4: 9,218.03 average ticks (over 10000 runs), 1.0X

是的!

工作台框架采用 Partridge 的道具,很容易破解。使用的输入是以下 SHA-1 哈希,重复 5000 次以形成 100,000 字节长的字符串。

209113288F93A9AB8E474EA78D899AFDBB874355

玩得开心!(但要适度优化。)

补充@CodesInChaos回答(反向方法)

public static byte[] HexToByteUsingByteManipulation(string s)
{
    byte[] bytes = new byte[s.Length / 2];
    for (int i = 0; i < bytes.Length; i++)
    {
        int hi = s[i*2] - 65;
        hi = hi + 10 + ((hi >> 31) & 7);

        int lo = s[i*2 + 1] - 65;
        lo = lo + 10 + ((lo >> 31) & 7) & 0x0f;

        bytes[i] = (byte) (lo | hi << 4);
    }
    return bytes;
}

说明:

& 0x0f也支持小写字母

hi = hi + 10 + ((hi >> 31) & 7);与:

相同

hi = ch-65 + 10 + (((ch-65) >> 31) & 7);

对于'0'..'9'它与hi = ch - 65 + 10 + 7;相同,这是hi = ch - 48(这是因为0xffffffff & 7)。

对于'A'..'F',它是hi = ch - 65 + 10;(这是因为0x00000000 & 7)。

对于'a'..'f',我们必须使用大数字,所以我们必须通过使用0使一些位'A'从默认版本中减去32。

65是'0'

的代码

48是'9'

的代码

7是ASCII表(...456789:;<=>?@ABCD...)中<=>和<=>之间的字母数。

这是一篇很棒的文章。我喜欢Waleed的解决方案。我还没有通过patridge的测试来运行它,但它看起来非常快。我还需要反向过程,将十六进制字符串转换为字节数组,因此我将其写为Waleed解决方案的逆转。不确定它是否比Tomalak的原始解决方案更快。同样,我也没有通过patridge的测试运行反向过程。

private byte[] HexStringToByteArray(string hexString)
{
    int hexStringLength = hexString.Length;
    byte[] b = new byte[hexStringLength / 2];
    for (int i = 0; i < hexStringLength; i += 2)
    {
        int topChar = (hexString[i] > 0x40 ? hexString[i] - 0x37 : hexString[i] - 0x30) << 4;
        int bottomChar = hexString[i + 1] > 0x40 ? hexString[i + 1] - 0x37 : hexString[i + 1] - 0x30;
        b[i / 2] = Convert.ToByte(topChar + bottomChar);
    }
    return b;
}

为什么要让它变得复杂?这在Visual <!>工作室<!> nbsp; 2008:

中很简单

C#:

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

VB:

Dim hex As String = BitConverter.ToString(YourByteArray).Replace("-", "")

不要在这里找到很多答案,但我发现了一个相当优化的(比接受的好4.5倍),十六进制字符串解析器的直接实现。首先,我的测试输出(第一批是我的实现):

Give me that string:
04c63f7842740c77e545bb0b2ade90b384f119f6ab57b680b7aa575a2f40939f

Time to parse 100,000 times: 50.4192 ms
Result as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=
BitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5
7-B6-80-B7-AA-57-5A-2F-40-93-9F

Accepted answer: (StringToByteArray)
Time to parse 100000 times: 233.1264ms
Result as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=
BitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5
7-B6-80-B7-AA-57-5A-2F-40-93-9F

With Mono's implementation:
Time to parse 100000 times: 777.2544ms
Result as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=
BitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5
7-B6-80-B7-AA-57-5A-2F-40-93-9F

With SoapHexBinary:
Time to parse 100000 times: 845.1456ms
Result as base64: BMY/eEJ0DHflRbsLKt6Qs4TxGfarV7aAt6pXWi9Ak58=
BitConverter'd: 04-C6-3F-78-42-74-0C-77-E5-45-BB-0B-2A-DE-90-B3-84-F1-19-F6-AB-5
7-B6-80-B7-AA-57-5A-2F-40-93-9F

base64和'BitConverter'd'行用于测试正确性。请注意它们是平等的。

实施:

public static byte[] ToByteArrayFromHex(string hexString)
{
  if (hexString.Length % 2 != 0) throw new ArgumentException("String must have an even length");
  var array = new byte[hexString.Length / 2];
  for (int i = 0; i < hexString.Length; i += 2)
  {
    array[i/2] = ByteFromTwoChars(hexString[i], hexString[i + 1]);
  }
  return array;
}

private static byte ByteFromTwoChars(char p, char p_2)
{
  byte ret;
  if (p <= '9' && p >= '0')
  {
    ret = (byte) ((p - '0') << 4);
  }
  else if (p <= 'f' && p >= 'a')
  {
    ret = (byte) ((p - 'a' + 10) << 4);
  }
  else if (p <= 'F' && p >= 'A')
  {
    ret = (byte) ((p - 'A' + 10) << 4);
  } else throw new ArgumentException("Char is not a hex digit: " + p,"p");

  if (p_2 <= '9' && p_2 >= '0')
  {
    ret |= (byte) ((p_2 - '0'));
  }
  else if (p_2 <= 'f' && p_2 >= 'a')
  {
    ret |= (byte) ((p_2 - 'a' + 10));
  }
  else if (p_2 <= 'F' && p_2 >= 'A')
  {
    ret |= (byte) ((p_2 - 'A' + 10));
  } else throw new ArgumentException("Char is not a hex digit: " + p_2, "p_2");

  return ret;
}

我用unsafe尝试了一些东西,并将(明显多余的)字符到nibble if序列移动到另一个方法,但这是它获得的最快。

(我承认这回答了问题的一半。我觉得字符串 - <!> gt; byte []转换的代表性不足,而字节[] - <!> gt;字符串角度似乎很好。因此,这个答案。)

安全版本:

public static class HexHelper
{
    [System.Diagnostics.Contracts.Pure]
    public static string ToHex(this byte[] value)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        const string hexAlphabet = @"0123456789ABCDEF";

        var chars = new char[checked(value.Length * 2)];
        unchecked
        {
            for (int i = 0; i < value.Length; i++)
            {
                chars[i * 2] = hexAlphabet[value[i] >> 4];
                chars[i * 2 + 1] = hexAlphabet[value[i] & 0xF];
            }
        }
        return new string(chars);
    }

    [System.Diagnostics.Contracts.Pure]
    public static byte[] FromHex(this string value)
    {
        if (value == null)
            throw new ArgumentNullException("value");
        if (value.Length % 2 != 0)
            throw new ArgumentException("Hexadecimal value length must be even.", "value");

        unchecked
        {
            byte[] result = new byte[value.Length / 2];
            for (int i = 0; i < result.Length; i++)
            {
                // 0(48) - 9(57) -> 0 - 9
                // A(65) - F(70) -> 10 - 15
                int b = value[i * 2]; // High 4 bits.
                int val = ((b - '0') + ((('9' - b) >> 31) & -7)) << 4;
                b = value[i * 2 + 1]; // Low 4 bits.
                val += (b - '0') + ((('9' - b) >> 31) & -7);
                result[i] = checked((byte)val);
            }
            return result;
        }
    }
}

不安全的版本对于那些喜欢表现并且不怕不安全的人。 ToHex快35%,FromHex快10%。

public static class HexUnsafeHelper
{
    [System.Diagnostics.Contracts.Pure]
    public static unsafe string ToHex(this byte[] value)
    {
        if (value == null)
            throw new ArgumentNullException("value");

        const string alphabet = @"0123456789ABCDEF";

        string result = new string(' ', checked(value.Length * 2));
        fixed (char* alphabetPtr = alphabet)
        fixed (char* resultPtr = result)
        {
            char* ptr = resultPtr;
            unchecked
            {
                for (int i = 0; i < value.Length; i++)
                {
                    *ptr++ = *(alphabetPtr + (value[i] >> 4));
                    *ptr++ = *(alphabetPtr + (value[i] & 0xF));
                }
            }
        }
        return result;
    }

    [System.Diagnostics.Contracts.Pure]
    public static unsafe byte[] FromHex(this string value)
    {
        if (value == null)
            throw new ArgumentNullException("value");
        if (value.Length % 2 != 0)
            throw new ArgumentException("Hexadecimal value length must be even.", "value");

        unchecked
        {
            byte[] result = new byte[value.Length / 2];
            fixed (char* valuePtr = value)
            {
                char* valPtr = valuePtr;
                for (int i = 0; i < result.Length; i++)
                {
                    // 0(48) - 9(57) -> 0 - 9
                    // A(65) - F(70) -> 10 - 15
                    int b = *valPtr++; // High 4 bits.
                    int val = ((b - '0') + ((('9' - b) >> 31) & -7)) << 4;
                    b = *valPtr++; // Low 4 bits.
                    val += (b - '0') + ((('9' - b) >> 31) & -7);
                    result[i] = checked((byte)val);
                }
            }
            return result;
        }
    }
}

<强>顺便说一句 对于每次调用转换函数错误时初始化字母表的基准测试,字母必须是const(对于字符串)或静态只读(对于char [])。然后,byte []到字符串的基于字母的转换变得和字节操作版本一样快。

当然,测试必须在Release(带优化)和debug选项<!>中进行编译;抑制JIT优化<!>关闭(相同于<!>“;启用我的代码<!>”;如果代码必须是可调试的。)

Waleed Eissa代码的反函数(Hex String To Byte Array):

    public static byte[] HexToBytes(this string hexString)        
    {
        byte[] b = new byte[hexString.Length / 2];            
        char c;
        for (int i = 0; i < hexString.Length / 2; i++)
        {
            c = hexString[i * 2];
            b[i] = (byte)((c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57)) << 4);
            c = hexString[i * 2 + 1];
            b[i] += (byte)(c < 0x40 ? c - 0x30 : (c < 0x47 ? c - 0x37 : c - 0x57));
        }

        return b;
    }

Waleed Eissa功能,支持小写:

    public static string BytesToHex(this byte[] barray, bool toLowerCase = true)
    {
        byte addByte = 0x37;
        if (toLowerCase) addByte = 0x57;
        char[] c = new char[barray.Length * 2];
        byte b;
        for (int i = 0; i < barray.Length; ++i)
        {
            b = ((byte)(barray[i] >> 4));
            c[i * 2] = (char)(b > 9 ? b + addByte : b + 0x30);
            b = ((byte)(barray[i] & 0xF));
            c[i * 2 + 1] = (char)(b > 9 ? b + addByte : b + 0x30);
        }

        return new string(c);
    }

扩展方法(免责声明:完全未经测试的代码,BTW ......):

public static class ByteExtensions
{
    public static string ToHexString(this byte[] ba)
    {
        StringBuilder hex = new StringBuilder(ba.Length * 2);

        foreach (byte b in ba)
        {
            hex.AppendFormat("{0:x2}", b);
        }
        return hex.ToString();
    }
}

等。使用 Tomalak的三个解决方案(最后一个是字符串的扩展方法)。

来自Microsoft的开发人员,一个简单的转换:

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

虽然上面的内容很简洁,但性能迷们会使用枚举器来尖叫它。使用改进版Tomolak的原始答案,您可以获得最佳性能:

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();   
} 

这是迄今为止我在此处发布的所有例程中最快的。不要只听我的话......对每个例程进行性能测试并自己检查它的CIL代码。

就速度而言,这似乎比这里的任何东西都好:

  public static string ToHexString(byte[] data) {
    byte b;
    int i, j, k;
    int l = data.Length;
    char[] r = new char[l * 2];
    for (i = 0, j = 0; i < l; ++i) {
      b = data[i];
      k = b >> 4;
      r[j++] = (char)(k > 9 ? k + 0x37 : k + 0x30);
      k = b & 15;
      r[j++] = (char)(k > 9 ? k + 0x37 : k + 0x30);
    }
    return new string(r);
  }

我没有得到你建议工作的代码,Olipro。 hex[i] + hex[i+1]显然返回了int

我做了,但是通过从Waleeds代码中获取一些提示并将其拼凑起来取得了一些成功。它很难看,但根据我的测试(使用patridges测试机制),它似乎在工作和执行时比其他时间高1/3。取决于输入大小。在?:s之间切换以首先分离0-9可能会产生稍快的结果,因为数字多于字母。

public static byte[] StringToByteArray2(string hex)
{
    byte[] bytes = new byte[hex.Length/2];
    int bl = bytes.Length;
    for (int i = 0; i < bl; ++i)
    {
        bytes[i] = (byte)((hex[2 * i] > 'F' ? hex[2 * i] - 0x57 : hex[2 * i] > '9' ? hex[2 * i] - 0x37 : hex[2 * i] - 0x30) << 4);
        bytes[i] |= (byte)(hex[2 * i + 1] > 'F' ? hex[2 * i + 1] - 0x57 : hex[2 * i + 1] > '9' ? hex[2 * i + 1] - 0x37 : hex[2 * i + 1] - 0x30);
    }
    return bytes;
}

此版本的 ByteArrayToHexViaByteManipulation 可能会更快。

从我的报告来看:

  • ByteArrayToHexViaByteManipulation3:1,68 平均刻度(超过 1000 次运行),17,5X
  • ByteArrayToHexViaByteManipulation2:1,73 平均刻度(超过 1000 次运行),16,9X
  • ByteArrayToHexViaByteManipulation:2,90 平均刻度(超过 1000 次运行),10,1X
  • ByteArrayToHexViaLookupAndShift:3,22 平均刻度(超过 1000 次运行),9,1X
  • ...

    static private readonly char[] hexAlphabet = new char[]
        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    static string ByteArrayToHexViaByteManipulation3(byte[] bytes)
    {
        char[] c = new char[bytes.Length * 2];
        byte b;
        for (int i = 0; i < bytes.Length; i++)
        {
            b = ((byte)(bytes[i] >> 4));
            c[i * 2] = hexAlphabet[b];
            b = ((byte)(bytes[i] & 0xF));
            c[i * 2 + 1] = hexAlphabet[b];
        }
        return new string(c);
    }
    

我认为这是一种优化:

    static private readonly char[] hexAlphabet = new char[]
        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    static string ByteArrayToHexViaByteManipulation4(byte[] bytes)
    {
        char[] c = new char[bytes.Length * 2];
        for (int i = 0, ptr = 0; i < bytes.Length; i++, ptr += 2)
        {
            byte b = bytes[i];
            c[ptr] = hexAlphabet[b >> 4];
            c[ptr + 1] = hexAlphabet[b & 0xF];
        }
        return new string(c);
    }

我将进入这个小小的竞争,因为我有一个答案,也使用了比特摆弄解码十六进制。请注意,使用字符数组可能会更快,因为调用StringBuilder方法也需要时间。

public static String ToHex (byte[] data)
{
    int dataLength = data.Length;
    // pre-create the stringbuilder using the length of the data * 2, precisely enough
    StringBuilder sb = new StringBuilder (dataLength * 2);
    for (int i = 0; i < dataLength; i++) {
        int b = data [i];

        // check using calculation over bits to see if first tuple is a letter
        // isLetter is zero if it is a digit, 1 if it is a letter
        int isLetter = (b >> 7) & ((b >> 6) | (b >> 5)) & 1;

        // calculate the code using a multiplication to make up the difference between
        // a digit character and an alphanumerical character
        int code = '0' + ((b >> 4) & 0xF) + isLetter * ('A' - '9' - 1);
        // now append the result, after casting the code point to a character
        sb.Append ((Char)code);

        // do the same with the lower (less significant) tuple
        isLetter = (b >> 3) & ((b >> 2) | (b >> 1)) & 1;
        code = '0' + (b & 0xF) + isLetter * ('A' - '9' - 1);
        sb.Append ((Char)code);
    }
    return sb.ToString ();
}

public static byte[] FromHex (String hex)
{

    // pre-create the array
    int resultLength = hex.Length / 2;
    byte[] result = new byte[resultLength];
    // set validity = 0 (0 = valid, anything else is not valid)
    int validity = 0;
    int c, isLetter, value, validDigitStruct, validDigit, validLetterStruct, validLetter;
    for (int i = 0, hexOffset = 0; i < resultLength; i++, hexOffset += 2) {
        c = hex [hexOffset];

        // check using calculation over bits to see if first char is a letter
        // isLetter is zero if it is a digit, 1 if it is a letter (upper & lowercase)
        isLetter = (c >> 6) & 1;

        // calculate the tuple value using a multiplication to make up the difference between
        // a digit character and an alphanumerical character
        // minus 1 for the fact that the letters are not zero based
        value = ((c & 0xF) + isLetter * (-1 + 10)) << 4;

        // check validity of all the other bits
        validity |= c >> 7; // changed to >>, maybe not OK, use UInt?

        validDigitStruct = (c & 0x30) ^ 0x30;
        validDigit = ((c & 0x8) >> 3) * (c & 0x6);
        validity |= (isLetter ^ 1) * (validDigitStruct | validDigit);

        validLetterStruct = c & 0x18;
        validLetter = (((c - 1) & 0x4) >> 2) * ((c - 1) & 0x2);
        validity |= isLetter * (validLetterStruct | validLetter);

        // do the same with the lower (less significant) tuple
        c = hex [hexOffset + 1];
        isLetter = (c >> 6) & 1;
        value ^= (c & 0xF) + isLetter * (-1 + 10);
        result [i] = (byte)value;

        // check validity of all the other bits
        validity |= c >> 7; // changed to >>, maybe not OK, use UInt?

        validDigitStruct = (c & 0x30) ^ 0x30;
        validDigit = ((c & 0x8) >> 3) * (c & 0x6);
        validity |= (isLetter ^ 1) * (validDigitStruct | validDigit);

        validLetterStruct = c & 0x18;
        validLetter = (((c - 1) & 0x4) >> 2) * ((c - 1) & 0x2);
        validity |= isLetter * (validLetterStruct | validLetter);
    }

    if (validity != 0) {
        throw new ArgumentException ("Hexadecimal encoding incorrect for input " + hex);
    }

    return result;
}

从Java代码转换。

为了表现,我会选择drphrozens解决方案。解码器的一个微小的优化可能是使用一个表来表示char,以摆脱<!>“<!> lt; <!> lt; 4 QUOT <!>;

显然,这两种方法调用成本很高。如果对输入或输出数据(可能是CRC,校验和或其他)进行某种检查,则可以跳过if (b == 255)...,从而也可以完全调用该方法。

使用offset++offset代替offset + 1和<=>可能会带来一些理论上的好处,但我怀疑编译器会比我更好地处理这个问题。

private static readonly byte[] LookupTableLow = new byte[] {
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};

private static readonly byte[] LookupTableHigh = new byte[] {
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
  0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF
};

private static byte LookupLow(char c)
{
  var b = LookupTableLow[c];
  if (b == 255)
    throw new IOException("Expected a hex character, got " + c);
  return b;
}

private static byte LookupHigh(char c)
{
  var b = LookupTableHigh[c];
  if (b == 255)
    throw new IOException("Expected a hex character, got " + c);
  return b;
}

public static byte ToByte(char[] chars, int offset)
{
  return (byte)(LookupHigh(chars[offset++]) | LookupLow(chars[offset]));
}

这只是我的头脑,并没有经过测试或基准测试。

用于插入SQL字符串(如果您没有使用命令参数):

public static String ByteArrayToSQLHexString(byte[] Source)
{
    return = "0x" + BitConverter.ToString(Source).Replace("-", "");
}

多样性的另一种变化:

public static byte[] FromHexString(string src)
{
    if (String.IsNullOrEmpty(src))
        return null;

    int index = src.Length;
    int sz = index / 2;
    if (sz <= 0)
        return null;

    byte[] rc = new byte[sz];

    while (--sz >= 0)
    {
        char lo = src[--index];
        char hi = src[--index];

        rc[sz] = (byte)(
            (
                (hi >= '0' && hi <= '9') ? hi - '0' :
                (hi >= 'a' && hi <= 'f') ? hi - 'a' + 10 :
                (hi >= 'A' && hi <= 'F') ? hi - 'A' + 10 :
                0
            )
            << 4 | 
            (
                (lo >= '0' && lo <= '9') ? lo - '0' :
                (lo >= 'a' && lo <= 'f') ? lo - 'a' + 10 :
                (lo >= 'A' && lo <= 'F') ? lo - 'A' + 10 :
                0
            )
        );
    }

    return rc;          
}

未针对速度进行优化,但比大多数答案(.NET 4.0)更多LINQy:

<Extension()>
Public Function FromHexToByteArray(hex As String) As Byte()
    hex = If(hex, String.Empty)
    If hex.Length Mod 2 = 1 Then hex = "0" & hex
    Return Enumerable.Range(0, hex.Length \ 2).Select(Function(i) Convert.ToByte(hex.Substring(i * 2, 2), 16)).ToArray
End Function

<Extension()>
Public Function ToHexString(bytes As IEnumerable(Of Byte)) As String
    Return String.Concat(bytes.Select(Function(b) b.ToString("X2")))
End Function

两个mashup将两个半字节操作折叠成一个。

可能效率很高的版本:

public static string ByteArrayToString2(byte[] ba)
{
    char[] c = new char[ba.Length * 2];
    for( int i = 0; i < ba.Length * 2; ++i)
    {
        byte b = (byte)((ba[i>>1] >> 4*((i&1)^1)) & 0xF);
        c[i] = (char)(55 + b + (((b-10)>>31)&-7));
    }
    return new string( c );
}

颓废的linq-with-bit-hacking版本:

public static string ByteArrayToString(byte[] ba)
{
    return string.Concat( ba.SelectMany( b => new int[] { b >> 4, b & 0xF }).Select( b => (char)(55 + b + (((b-10)>>31)&-7))) );
}

反过来:

public static byte[] HexStringToByteArray( string s )
{
    byte[] ab = new byte[s.Length>>1];
    for( int i = 0; i < s.Length; i++ )
    {
        int b = s[i];
        b = (b - '0') + ((('9' - b)>>31)&-7);
        ab[i>>1] |= (byte)(b << 4*((i&1)^1));
    }
    return ab;
}

另一种方法是使用stackalloc来降低GC内存压力:

static string ByteToHexBitFiddle(byte[] bytes)
{
        var c = stackalloc char[bytes.Length * 2 + 1];
        int b; 
        for (int i = 0; i < bytes.Length; ++i)
        {
            b = bytes[i] >> 4;
            c[i * 2] = (char)(55 + b + (((b - 10) >> 31) & -7));
            b = bytes[i] & 0xF;
            c[i * 2 + 1] = (char)(55 + b + (((b - 10) >> 31) & -7));
        }
        c[bytes.Length * 2 ] = '\0';
        return new string(c);
}

这是我的镜头。我已经创建了一对扩展类来扩展字符串和字节。在大文件测试中,性能与Byte Manipulation 2相当。

以下ToHexString代码是查找和移位算法的优化实现。它几乎与Behrooz的相同,但事实证明使用foreach进行迭代并且计数器比显式索引for更快。

它在我的机器上的Byte Manipulation 2后面排在第二位,并且代码非常易读。以下测试结果也很有意义:

ToHexStringCharArrayWithCharArrayLookup:41,589.69平均价格(超过1000次运行),1.5X ToHexStringCharArrayWithStringLookup:50,764.06平均刻度(超过1000次运行),1.2X ToHexStringStringBuilderWithCharArrayLookup:62,812.87平均价格(超过1000次运行),1.0X

基于上述结果,似乎可以得出结论:

  1. 索引到字符串以执行查找与a的惩罚 char数组在大文件测试中很重要。
  2. 使用已知容量的StringBuilder与char的惩罚 用于创建字符串的已知大小的数组甚至更为重要。
  3. 以下是代码:

    using System;
    
    namespace ConversionExtensions
    {
        public static class ByteArrayExtensions
        {
            private readonly static char[] digits = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    
            public static string ToHexString(this byte[] bytes)
            {
                char[] hex = new char[bytes.Length * 2];
                int index = 0;
    
                foreach (byte b in bytes)
                {
                    hex[index++] = digits[b >> 4];
                    hex[index++] = digits[b & 0x0F];
                }
    
                return new string(hex);
            }
        }
    }
    
    
    using System;
    using System.IO;
    
    namespace ConversionExtensions
    {
        public static class StringExtensions
        {
            public static byte[] ToBytes(this string hexString)
            {
                if (!string.IsNullOrEmpty(hexString) && hexString.Length % 2 != 0)
                {
                    throw new FormatException("Hexadecimal string must not be empty and must contain an even number of digits to be valid.");
                }
    
                hexString = hexString.ToUpperInvariant();
                byte[] data = new byte[hexString.Length / 2];
    
                for (int index = 0; index < hexString.Length; index += 2)
                {
                    int highDigitValue = hexString[index] <= '9' ? hexString[index] - '0' : hexString[index] - 'A' + 10;
                    int lowDigitValue = hexString[index + 1] <= '9' ? hexString[index + 1] - '0' : hexString[index + 1] - 'A' + 10;
    
                    if (highDigitValue < 0 || lowDigitValue < 0 || highDigitValue > 15 || lowDigitValue > 15)
                    {
                        throw new FormatException("An invalid digit was encountered. Valid hexadecimal digits are 0-9 and A-F.");
                    }
                    else
                    {
                        byte value = (byte)((highDigitValue << 4) | (lowDigitValue & 0x0F));
                        data[index / 2] = value;
                    }
                }
    
                return data;
            }
        }
    }
    

    以下是我在我的机器上将代码放入@ patridge的测试项目时得到的测试结果。我还添加了一个从十六进制转换为字节数组的测试。执行我的代码的测试运行是ByteArrayToHexViaOptimizedLookupAndShift和HexToByteArrayViaByteManipulation。 HexToByteArrayViaConvertToByte取自XXXX。 HexToByteArrayViaSoapHexBinary来自@ Mykroft的回答。

      

    Intel Pentium III Xeon处理器

        Cores: 4 <br/>
        Current Clock Speed: 1576 <br/>
        Max Clock Speed: 3092 <br/>
    
         
         

    将字节数组转换为十六进制字符串表示

         
         

    ByteArrayToHexViaByteManipulation2:39,366.64平均价格(超过1000次运行),22.4X

         

    ByteArrayToHexViaOptimizedLookupAndShift:41,588.64平均价格   (超过1000次运行),21.2X

         

    ByteArrayToHexViaLookup:55,509.56平均价格(超过1000次运行),15.9X

         

    ByteArrayToHexViaByteManipulation:65,349.12平均价格(超过1000次运行),13.5X

         

    ByteArrayToHexViaLookupAndShift:86,926.87平均价格(超过1000)   运行),10.2X

         

    ByteArrayToHexStringViaBitConverter:平均139,353.73   蜱(超过1000次运行),6.3X

         

    ByteArrayToHexViaSoapHexBinary:314,598.77平均价格(超过1000次运行),2.8X

         

    ByteArrayToHexStringViaStringBuilderForEachByteToString:344,264.63   平均价格(超过1000次运行),2.6X

         

    ByteArrayToHexStringViaStringBuilderAggregateByteToString:382,623.44   平均价格(超过1000次运行),2.3X

         

    ByteArrayToHexStringViaStringBuilderForEachAppendFormat:818,111.95   平均蜱(超过1000次运行),1.1X

         

    ByteArrayToHexStringViaStringConcatArrayConvertAll:平均839,244.84   蜱(超过1000次运行),1.1X

         

    ByteArrayToHexStringViaStringBuilderAggregateAppendFormat:867,303.98   平均蜱(超过1000次运行),1.0X

         

    ByteArrayToHexStringViaStringJoinArrayConvertAll:平均882,710.28   滴答(超过1000次运行),1.0X

         

另一个快速功能......

private static readonly byte[] HexNibble = new byte[] {
    0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7,
    0x8, 0x9, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
    0x0, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF
};

public static byte[] HexStringToByteArray( string str )
{
    int byteCount = str.Length >> 1;
    byte[] result = new byte[byteCount + (str.Length & 1)];
    for( int i = 0; i < byteCount; i++ )
        result[i] = (byte) (HexNibble[str[i << 1] - 48] << 4 | HexNibble[str[(i << 1) + 1] - 48]);
    if( (str.Length & 1) != 0 )
        result[byteCount] = (byte) HexNibble[str[str.Length - 1] - 48];
    return result;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top