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