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
Yet another variation for diversity:
Not to pile on to the many answers here, but I found a fairly optimal (~4.5x better than accepted), straightforward implementation of the hex string parser. First, output from my tests (the first batch is my implementation):
The base64 and 'BitConverter'd' lines are there to test for correctness. Note that they are equal.
The implementation:
I tried some stuff with
unsafe
and moving the (clearly redundant) character-to-nibbleif
sequence to another method, but this was the fastest it got.(I concede that this answers half the question. I felt that the string->byte[] conversion was underrepresented, while the byte[]->string angle seems to be well covered. Thus, this answer.)
Another lookup table based approach. This one uses only one lookup table for each byte, instead of a lookup table per nibble.
I also tested variants of this using
ushort
,struct{char X1, X2}
,struct{byte X1, X2}
in the lookup table.Depending on the compilation target (x86, X64) those either had the approximately same performance or were slightly slower than this variant.
And for even higher performance, its
unsafe
sibling:Or if you consider it acceptable to write into the string directly:
Why make it complex? This is simple in Visual Studio 2008:
C#:
VB:
Two mashups which folds the two nibble operations into one.
Probably pretty efficient version:
Decadent linq-with-bit-hacking version:
And reverse:
This is a great post. I like Waleed's solution. I haven't run it through patridge's test but it seems to be quite fast. I also needed the reverse process, converting a hex string to a byte array, so I wrote it as a reversal of Waleed's solution. Not sure if it's any faster than Tomalak's original solution. Again, I did not run the reverse process through patridge's test either.