Skip to content

Instantly share code, notes, and snippets.

@jchandra74
Created April 14, 2015 00:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jchandra74/99a2eb8e9d12555ce90e to your computer and use it in GitHub Desktop.
Save jchandra74/99a2eb8e9d12555ce90e to your computer and use it in GitHub Desktop.
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