Skip to content

Instantly share code, notes, and snippets.

@edamtoft
Created December 18, 2019 17:22
Show Gist options
  • Save edamtoft/549a56853008772a085802469b65ad1b to your computer and use it in GitHub Desktop.
Save edamtoft/549a56853008772a085802469b65ad1b to your computer and use it in GitHub Desktop.
High Performance byte[] to Hex String Converter.
public static class HexUtils
{
public static string ToHexString(byte[] bytes)
{
return string.Create(bytes.Length * 2, bytes, (chars, buffer) =>
{
for (var i = 0; i < buffer.Length; i += 2)
{
var b = buffer[i / 2];
chars[i] = GetHexChar(b / 16);
chars[i + 1] = GetHexChar(b % 16);
}
});
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static char GetHexChar(int i)
{
return i > 9
? (char)(i - 10 + 'a')
: (char)(i + '0');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment