Created
February 5, 2011 20:48
-
-
Save underhilllabs/812774 to your computer and use it in GitHub Desktop.
binary to hex converter
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
# binary to hexidecimal | |
def bin_to_hex(num): | |
total = "" | |
subtotal = 0 | |
i = 0 | |
numstr = str(num) | |
while(numstr): | |
# foreach digit of the nibble (4 binary digits) translate into single hex digit | |
# start from least sig digit | |
subtotal = 0 | |
# pad front of numbers with 0's to fill to 4 bits | |
if len(numstr) < 4: | |
numstr = "0"*(4-len(numstr))+numstr | |
for i in range(1,5): | |
dig = numstr[-i] | |
subtotal += int(dig) * int(pow(2,i-1)) | |
if (subtotal < 10): | |
total = str(subtotal) + total | |
else: | |
# 65 - 9 = | |
total = chr(subtotal-10+65) + total | |
# slice off last 4 bits and loop again | |
numstr = numstr[:-4] | |
return total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment