Created
April 14, 2015 00:12
-
-
Save jchandra74/99a2eb8e9d12555ce90e to your computer and use it in GitHub Desktop.
Binary to Hex String Conversion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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