Skip to content

Instantly share code, notes, and snippets.

@mstum
Created March 4, 2018 08:03
Show Gist options
  • Save mstum/7121f1f8a65eb45c70c502f15f95d218 to your computer and use it in GitHub Desktop.
Save mstum/7121f1f8a65eb45c70c502f15f95d218 to your computer and use it in GitHub Desktop.
Efficient byte[] to string
// Taken from https://www.bouncycastle.org/
// Adapted to create and return a string rather than write to a Stream
// https://twitter.com/mstum/status/970207754207006720
private static readonly byte[] encodingTable =
{
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7',
(byte)'8', (byte)'9', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f'
};
public static string ToHexBouncyCastle(byte[] data, int off, int length)
{
var result = new byte[length * 2];
var ix = 0;
for (int i = off; i < (off + length); i++)
{
int v = data[i];
result[ix++] = encodingTable[v >> 4];
result[ix++] = encodingTable[v & 0xf];
}
return Encoding.ASCII.GetString(result, 0, result.Length);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment