我有一个十六进制字符串,我需要转换为字节数组.最好的方法(即有效和最少的代码)是:
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);
}
Run Code Online (Sandbox Code Playgroud)
在我有32位值的情况下,我可以执行以下操作:
string hexstr = "683A2134";
byte[] bytes = BitConverter.GetBytes(Convert.ToInt32(hexstr, 16));
Run Code Online (Sandbox Code Playgroud)
然而,在一般情况下呢?有没有更好的内置功能,或更清晰(不必更快,但仍然高性能)这样做的方式?
我更喜欢内置函数,因为除了这个特殊的转换之外,似乎有一个用于所有东西(很常见的东西).
如果从字符代码计算值而不是创建子字符串并解析它们,则可以获得最佳性能.
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;
}
Run Code Online (Sandbox Code Playgroud)
用法:
byte[] bytes = ParseHexString("1fAB44AbcDEf00");
Run Code Online (Sandbox Code Playgroud)
由于代码使用了一些技巧,这里有一个注释版本:
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;
}
Run Code Online (Sandbox Code Playgroud)