问题描述
我有我需要转换为一个字节数组十六进制字符串。最好的办法(即高效,至少code)为:
I have a hexidecimal string that I need to convert to a byte array. The best way (ie efficient and least code) is:
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位的值,我可以做以下的情况:
In the case where I have a 32bit value I can do the following:
string hexstr = "683A2134";
byte[] bytes = BitConverter.GetBytes(Convert.ToInt32(hexstr, 16));
但是怎么样在一般情况下?有没有更好的内置函数,或者这样做更清晰的(并不一定会更快,但仍高性能)的方式?
However what about in the general case? Is there a better built in function, or a clearer (doesn't have to be faster, but still performant) way of doing this?
我会preFER一个内置的功能似乎有一个用于一切(以及共同的东西),除了这个特殊的转换。
I would prefer a built in function as there seems to be one for everything (well common things) except this particular conversion.
推荐答案
您如果从字符codeS计算创建子和解析它们的值,而不是获得最佳的性能。
You get the best performance if you calculate the values from the character codes instead of creating substrings and parsing them.
code在C#中,处理大写和小写的十六进制(但没有验证):
Code in C#, that handles both upper and lower case hex (but no validation):
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");
由于code使用一些技巧,这里有个注释的版本:
As the code uses a few tricks, here a commented version:
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)的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!