Skip to content

Instantly share code, notes, and snippets.

@edamtoft
Last active December 18, 2019 18:09
Show Gist options
  • Save edamtoft/239b9af04ad5d22f5aab36d409b5167d to your computer and use it in GitHub Desktop.
Save edamtoft/239b9af04ad5d22f5aab36d409b5167d to your computer and use it in GitHub Desktop.
High Performance byte[] to Hex String Converter
public static class HexUtils
{
private const string HexAlphabet = "0123456789abcdef";
public static string ToHexString(byte[] bytes)
{
return string.Create(bytes.Length * 2, bytes, (chars, buffer) =>
{
var charIndex = 0;
var bufferIndex = 0;
while (charIndex < chars.Length)
{
var b = buffer[bufferIndex];
chars[charIndex] = HexAlphabet[b / 16];
chars[charIndex + 1] = HexAlphabet[b % 16];
bufferIndex++;
charIndex += 2;
}
});
}
}
@edamtoft
Copy link
Author

edamtoft commented Dec 18, 2019

When run against the same profiler this is measurably faster than even the fastest algorithm included in this stack overflow answer, and considerably faster than the the accepted answer.

Results:
=== Long string test
BitConvertReplace calculation Time Elapsed 11146 ms
StringBuilder calculation Time Elapsed 27168 ms
LinqConcat calculation Time Elapsed 79051 ms
LinqJoin calculation Time Elapsed 82620 ms
LinqAgg calculation Time Elapsed 33217 ms
ToHex calculation Time Elapsed 5311 ms
ByteArrayToHexString calculation Time Elapsed 4194 ms
HexUtils.ToHexString calculation Time Elapsed 2054 ms
=== Many string test
BitConvertReplace calculation Time Elapsed 10773 ms
StringBuilder calculation Time Elapsed 26770 ms
LinqConcat calculation Time Elapsed 32131 ms
LinqJoin calculation Time Elapsed 34074 ms
LinqAgg calculation Time Elapsed 32890 ms
ToHex calculation Time Elapsed 4415 ms
ByteArrayToHexString calculation Time Elapsed 3168 ms
HexUtils.ToHexString calculation Time Elapsed 1831 ms

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment