byte[] 转十六进制字符串
如何将 byte[]
转换为 string
? 每次我尝试时,我都会得到
系统.Byte[]
而不是值。
另外,如何获取十六进制而不是十进制的值?
How do I convert a byte[]
to a string
? Every time I attempt it, I get
System.Byte[]
instead of the value.
Also, how do I get the value in Hex instead of a decimal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
有一个内置方法可以实现此目的:
结果:01-02-04-08-10-20
如果您希望不带破折号,只需将其删除即可:
结果:010204081020
如果您想要更紧凑的表示形式,可以使用 Base64:
结果:AQIECBAg
There is a built in method for this:
Result: 01-02-04-08-10-20
If you want it without the dashes, just remove them:
Result: 010204081020
If you want a more compact representation, you can use Base64:
Result: AQIECBAg
.Net5.0 更新
感谢@antoninkriz 的基准比较,我们可以看到
Convert.ToHexString
是到目前为止 今天明显的赢家如果您使用
Convert.ToHexString
以外的任何东西,那就太愚蠢了。 在我看来,它显然在以下方面获胜:可读性、性能、安全性其余部分来自 2012 年 4 月 10 日之前:
我想我应该尝试比较这里列出的每种方法的速度。 我基于此进行速度测试代码。
结果是 BitConverter+String .Replace 似乎比大多数其他简单方法更快。 但可以通过 Nathan Moinvaziri 的 ByteArrayToHexString 或 Kurt 的 ToHex 等算法来提高速度。
我还发现有趣的是,对于长字符串, string.Concat 和 string.Join 比 StringBuilder 实现慢得多,但对于较短的数组则类似。 可能是由于在较长的字符串上扩展了 StringBuilder,因此设置初始大小应该可以消除这种差异。
Convert.ToHexString
)Convert.ToHexString
)我使用的测试代码:
还有一个具有类似过程的答案,我还没有'还没有比较我们的结果。
.Net5.0 Update
Thanks to @antoninkriz's benchmark comparison we can see that
Convert.ToHexString
is by far the clear winner todayYou'd be foolish to use anything other than
Convert.ToHexString
. In my opinion it clearly wins in: readability, performance, safetyThe rest of this is from before Apr 10, 2012:
I thought I would attempt to compare the speed of each of the methods listed here for the hell of it. I based the speed testing code off this.
The result is that BitConverter+String.Replace seems to be faster than most other simple ways. But the speed can be improved with algorithms like Nathan Moinvaziri's ByteArrayToHexString or Kurt's ToHex.
I also found it interesting that string.Concat and string.Join are much slower than StringBuilder implementations for long strings, but similar for shorter arrays. Probably due to expanding the StringBuilder on the longer strings, so setting the initial size should negate this difference.
Convert.ToHexString
)Convert.ToHexString
)Testing code I used:
Also another answer with a similar process, I haven't compared our results yet.
十六进制,Linq-fu:
随时间更新
正如 @RubenBartelink 所指出的,没有将
IEnumerable
转换为数组的代码:ba.Select(b => b.ToString("X2"))
在 4.0 之前不起作用,相同的代码现在可以在 4.0 上运行。此代码...
...在 .NET 4.0 之前,输出为:
在 .NET 4.0 及以上版本中, string.Concat 具有接受 IEnumerable 的重载。 因此,在 4.0 上,上述代码对于变量 s 和 t 将具有相同的输出
在 4.0 之前,
ba.Select(b => b.ToString("X2"))
会重载(object arg0)
,IEnumerable
进行适当重载的方式,即(params string[] value)
,是我们需要将IEnumerable
转换为字符串数组。 在 4.0 之前, string.Concat 有 10 个重载函数,在 4.0 上现在是 12 个Hex, Linq-fu:
UPDATE with the times
As noted by @RubenBartelink, the code that don't have a conversion of
IEnumerable<string>
to an array:ba.Select(b => b.ToString("X2"))
does not work prior to 4.0, the same code is now working on 4.0.This code...
...prior to .NET 4.0, the output is:
On .NET 4.0 onwards, string.Concat has an overload that accepts IEnumerable. Hence on 4.0, the above code will have same output for both variables s and t
Prior to 4.0,
ba.Select(b => b.ToString("X2"))
goes to overload(object arg0)
, the way for theIEnumerable<string>
to go to a proper overload, i.e.(params string[] values)
, is we need to convert theIEnumerable<string>
to string array. Prior to 4.0, string.Concat has 10 overload functions, on 4.0 it is now 12这是另一种方法:
或者,您可以像这样预先构建翻译表以获得更快的结果:
http://blogs.msdn.com/b/blambert/archive/2009/02/22/blambert- codenip-fast-byte-array-to-hex-string-conversion.aspx
Here is another method:
Alternatively, you could pre-build the translation table like so to achieve even faster results:
http://blogs.msdn.com/b/blambert/archive/2009/02/22/blambert-codesnip-fast-byte-array-to-hex-string-conversion.aspx
我喜欢使用扩展方法进行这样的转换,即使它们只是包装标准库方法。 对于十六进制转换,我使用以下手动调整(即快速)算法:
I like using extension methods for conversions like this, even if they just wrap standard library methods. In the case of hexadecimal conversions, I use the following hand-tuned (i.e., fast) algorithms:
好吧,我不经常将字节转换为十六进制,所以我不得不说我不知道是否有更好的方法,但这里有一种方法。
Well I don't convert bytes to hex often so I have to say I don't know if there is a better way then this, but here is a way to do it.
我想我应该提供一个答案。 根据我的测试,这种方法是最快的
I thought I should provide an answer. From my test this method is the fastest
非常快的扩展方法(带反转):
在上面的速度测试中击败所有其他方法:
Very fast extension methods (with reversal):
Beats all the others in the speed test above:
只是为了在一堆答案中添加一个答案,我使用了一个 System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary 类,它可以将字节与十六进制相互转换:
不知道它是如何实现的与其他实现进行比较(基准),但在我看来,它非常简单——尤其是从十六进制转换回字节。
Just to add one more answer to the pile, there is a
System.Runtime.Remoting.Metadata.W3cXsd2001.SoapHexBinary
class that I've used which can convert bytes to and from hex:Not sure how it compares (benchmark) to other implementations, but IMO it is pretty simple -- especially for converting from hex back into bytes.
其中:
结果:
0102030d0e0f
With:
Result:
0102030d0e0f
您必须知道以字节表示的字符串的编码,但您可以说
System.Text.UTF8Encoding.GetString(bytes)
或System.Text.ASCIIEncoding.GetString(bytes)
代码>. (我是凭记忆做的,所以 API 可能不完全正确,但非常接近。)有关第二个问题的答案,请参阅 这个问题。
You have to know the encoding of the string represented in bytes, but you can say
System.Text.UTF8Encoding.GetString(bytes)
orSystem.Text.ASCIIEncoding.GetString(bytes)
. (I'm doing this from memory, so the API may not be exactly correct, but it's very close.)For the answer to your second question, see this question.
这是字节数组(byte[])的扩展方法,例如,
Here is a extension method for byte array (byte[]), e.g.,
您可以将 LINQ 与字符串方法结合起来:
You combine LINQ with string methods:
这里没有人提到为什么你得到“System.Byte[]”字符串而不是值,所以我会的。
当一个对象隐式转换为 String 时,程序将默认使用该对象的
public String ToString()
方法,该方法继承自System.Object
:如果您发现如果经常进行这种转换,您可以简单地创建一个包装类并重写此方法,如下所示:
现在,每次打印此包装对象时,您将获得您的值,而不是
this.GetType().ToString() 中的值
。No one here mentioned the reason why you get the "System.Byte[]" string instead of the value, so I will.
When an object is implicitly cast to a String, the program will default to the object's
public String ToString()
method which is inherited fromSystem.Object
:If you find that you are often making this conversion, you could simply create a wrapper class and override this method like so:
Now each time you print this wrapper object you will get your value instead of the value from
this.GetType().ToString()
.正如其他人所说,这取决于字节数组中值的编码。 尽管如此,您需要非常小心处理此类事情,否则您可能会尝试转换所选编码未处理的字节。
Jon Skeet 有一篇关于 .NET 中的编码和 unicode 的好文章。 推荐阅读。
As others have said it depends on the encoding of the values in the byte array. Despite this you need to be very careful with this sort of thing or you may try to convert bytes that are not handled by the chosen encoding.
Jon Skeet has a good article about encoding and unicode in .NET. Recommended reading.
我想我制作了一个更快的字节数组到字符串转换器:
测试设置:
ToHexChar.ToHEx() 方法是前面显示的 ToHex() 方法。
结果如下:
HexTable = 11808 ms
ToHEx = 12168ms
它可能看起来没有太大区别,但它仍然更快:)
I think I made a faster byte array to string convertor:
And the test set up:
The ToHexChar.ToHEx() method is the ToHex() method shown previously.
Results are as follows:
HexTable = 11808 ms
ToHEx = 12168ms
It may not look that much of a difference, but it's still faster :)
我不确定您是否需要执行此操作的性能,但这是我能想到的将 byte[] 转换为十六进制字符串的最快方法:
I'm not sure if you need perfomance for doing this, but here is the fastest method to convert byte[] to hex string that I can think of :
使用 LINQ 执行此操作的好方法...
Nice way to do this with LINQ...