Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa?
I need an efficient and fast way to do this conversion. I have tried two different ways, but they are not efficient enough for me. Is there any other quick method to accomplish this in a real-time fashion for an application with huge data?
public byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length / 2).Select(x => Byte.Parse(hex.Substring(2 * x, 2), NumberStyles.HexNumber)).ToArray();
}
The above one felt more efficient to me.
public static byte[] stringTobyte(string hexString)
{
try
{
int bytesCount = (hexString.Length) / 2;
byte[] bytes = new byte[bytesCount];
for (int x = 0; x < bytesCount; ++x)
{
bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
}
return bytes;
}
catch
{
throw;
}
I took the benchmarking code from the other question, and reworked it to test the hex to bytes methods given here:
HexToBytesJon
is Jon's first version, andHexToBytesJon2
is the second variant.HexToBytesJonCiC
is Jon's version with CodesInChaos's suggested code.HexToBytesJase
is my attempt, based on both the above but with alternative nybble conversion which eschews error checking, and branching:If you really need efficiency then:
Or, and get rid of
try
blocks which only have acatch
block which rethrows... for simplicity rather than efficiency though.This would be a pretty efficient version:
The TODO refers to an alternative like this. I haven't measured which is faster.
As a variant of Jon's
if
basedParseNybble
: