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