How can you convert a byte array to a hexadecimal string, and vice versa?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
If you want more flexibility than
BitConverter
, but don't want those clunky 1990s-style explicit loops, then you can do:Or, if you're using .NET 4.0:
(The latter from a comment on the original post.)
You can use the BitConverter.ToString method:
Output:
More information: BitConverter.ToString Method (Byte[])
I just encountered the very same problem today, and I came across this code:
Source: Forum post byte[] Array to Hex String (see the post by PZahra). I modified the code a little to remove the 0x prefix.
I did some performance testing to the code and it was almost eight times faster than using BitConverter.ToString() (the fastest according to patridge's post).
Extension methods (disclaimer: completely untested code, BTW...):
etc.. Use either of Tomalak's three solutions (with the last one being an extension method on a string).
Not optimized for speed, but more LINQy than most answers (.NET 4.0):
I'll enter this bit fiddling competition as I have an answer that also uses bit-fiddling to decode hexadecimals. Note that using character arrays may be even faster as calling
StringBuilder
methods will take time as well.Converted from Java code.