将十六进制字符串转换为字节数组 (.NET) 的最佳方法是什么?
我有一个十六进制字符串,需要将其转换为字节数组。 最好的方法(即高效和最少的代码)是:
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));
但是在一般情况下呢? 是否有更好的内置函数,或者更清晰的(不一定更快,但仍然高性能)的方法来做到这一点?
我更喜欢一个内置函数,因为除了这个特定的转换之外,似乎所有东西(常见的东西)都有一个。
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);
}
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?
I would prefer a built in function as there seems to be one for everything (well common things) except this particular conversion.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您根据字符代码计算值而不是创建子字符串并解析它们,则可以获得最佳性能。
C# 代码,处理大写和小写十六进制(但没有验证):
用法:
由于代码使用了一些技巧,这里有一个带注释的版本:
You get the best performance if you calculate the values from the character codes instead of creating substrings and parsing them.
Code in C#, that handles both upper and lower case hex (but no validation):
Usage:
As the code uses a few tricks, here a commented version:
不幸的是,没有内置任何东西。 (我真的应该把我在这里得到的代码放在其他地方 - 这至少是我第三次或第四次编写它。)
您当然可以创建一个更有效的版本,它从 char 解析 nybble 而不是采用子字符串每次,但代码更多。 如果您经常使用它,请首先对原始代码进行基准测试,看看它是否足够。
There's nothing built-in, unfortunately. (I really should have the code I've got here somewhere else - it's at least the 3rd or 4th time I've written it.)
You could certainly create a more efficient version which parsed a nybble from a char rather than taking a substring each time, but it's more code. If you're using this a lot, benchmark the original code to see whether or not it's adequate first.
看看这个 - 它非常短,是 .NET 框架的一部分:
System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse("C3B01051359947").Value
Take a look at this - it's very short and is part of the .NET framework:
System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary.Parse("C3B01051359947").Value
这是使用 LINQ 的单行代码。 它基本上只是原始版本的翻译:
如果您可能需要转换长度不均匀的字符串(即,如果它们可能有隐式前导零),那么代码会变得更复杂一些:
Here's a one-liner using LINQ. It's basically just a translation of your original version:
If you'll potentially need to convert strings of uneven length (ie, if they might have an implicit leading-zero) then the code becomes a bit more complicated: