.net - 将十六进制字符串转换为字节数组 (.NET) 的最佳方法是什么?

标签 .net hex

我有一个十六进制字符串,需要将其转换为字节数组。最好的方法(即高效和最少的代码)是:

string hexstr = "683A2134";
byte[] bytes = new byte[hexstr.Length/2];
for(int x = 0; x < bytes.Length; x++)
{
    bytes[x] = Convert.ToByte(hexstr.Substring(x * 2, 2), 16);
}

如果我有一个 32 位值,我可以执行以下操作:

string hexstr = "683A2134";
byte[] bytes = BitConverter.GetBytes(Convert.ToInt32(hexstr, 16)); 

但是在一般情况下呢?是否有更好的内置函数或更清晰(不必更快,但仍然高效)的方法?

我更喜欢内置函数,因为除了这个特定的转换之外,似乎所有东西(很常见的东西)都有一个内置函数。

最佳答案

如果您从字符代码计算值而不是创建子字符串并解析它们,您将获得最佳性能。

C# 中的代码,处理大写和小写的十六进制(但没有验证):

static byte[] ParseHexString(string hex) {
    byte[] bytes = new byte[hex.Length / 2];
    int shift = 4;
    int offset = 0;
    foreach (char c in hex) {
        int b = (c - '0') % 32;
        if (b > 9) b -= 7;
        bytes[offset] |= (byte)(b << shift);
        shift ^= 4;
        if (shift != 0) offset++;
    }
    return bytes;
}

用法:

byte[] bytes = ParseHexString("1fAB44AbcDEf00");

由于代码使用了一些技巧,这里是注释版本:

static byte[] ParseHexString(string hex) {
    // array to put the result in
    byte[] bytes = new byte[hex.Length / 2];
    // variable to determine shift of high/low nibble
    int shift = 4;
    // offset of the current byte in the array
    int offset = 0;
    // loop the characters in the string
    foreach (char c in hex) {
        // get character code in range 0-9, 17-22
        // the % 32 handles lower case characters
        int b = (c - '0') % 32;
        // correction for a-f
        if (b > 9) b -= 7;
        // store nibble (4 bits) in byte array
        bytes[offset] |= (byte)(b << shift);
        // toggle the shift variable between 0 and 4
        shift ^= 4;
        // move to next byte
        if (shift != 0) offset++;
    }
    return bytes;
}

关于.net - 将十六进制字符串转换为字节数组 (.NET) 的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/684925/

相关文章:

.net - 作为服务运行时找不到 PowerShell 模块

c# - 如何将 DataGridView 绑定(bind)到 SQLite 数据库?

c++ - 如何将二进制 IPv6 地址转换为十六进制

ios - 将表示十六进制值的 NSString 转换为十六进制( @"0d"到 0x0d)

python - 十六进制到字符串,python 方式,在 powershell 中

c - 从二进制文件中读取十六进制

.net - Winforms 样式/UI 外观和感觉提示

c# - 将报告逻辑移动到 .NET 代码 : Releasing fixes?

c# - 如何以正确的方式管理 mysql 连接而不会出错

python - 如何通过 Python socket.send() 发送字符串以外的任何内容