我有一个十六进制字符串,需要将其转换为字节数组。最好的方法(即高效和最少的代码)是:
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;
}
Usage:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)