Skip to content

Instantly share code, notes, and snippets.

@underhilllabs
Created February 5, 2011 21:28
Show Gist options
  • Save underhilllabs/812805 to your computer and use it in GitHub Desktop.
Save underhilllabs/812805 to your computer and use it in GitHub Desktop.
binary to octal conversion
# 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