Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Binary to Hex String Conversion
public static string BinaryToHex(byte[] data)
{
if (data == null)
{
return null;
}
var array = new char[checked(data.Length*2)];
for (var i = 0; i < data.Length; i++)
{
var b = data[i];
array[2*i] = NibbleToHex((byte) (b >> 4));
array[2*i + 1] = NibbleToHex((byte) (b & 15));
}
return new string(array);
}
private static char NibbleToHex(byte nibble)
{
/*
* f(x)
* where
* x = 0..9 -> x
* x = 10..15 -> x - 10 + 65 //65 = ASCII CODE for uppercased 'A'
*/
return (char) ((nibble < 10) ? (nibble + 48) : (nibble - 10 + 65));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.