Skip to content

Instantly share code, notes, and snippets.

@SuborbitalPigeon
Last active October 12, 2015 07:07
Show Gist options
  • Save SuborbitalPigeon/3989399 to your computer and use it in GitHub Desktop.
Save SuborbitalPigeon/3989399 to your computer and use it in GitHub Desktop.
Number to base
#!/usr/bin/env python
class Converter:
"""A bunch of converters"""
def __init__(self, number):
self.number = number
def to_base(self, digits):
# TODO: make the digits automatic and input the base instead
div = self.number
base = ""
n = len(digits)
while(div != 0):
(div, mod)= divmod(div, n)
base += digits[mod]
print("The number to the base {} is {}".format(n, base[::-1]))
def to_bin(self):
self.to_base("01")
def to_oct(self):
self.to_base("01234567")
def to_hex(self):
self.to_base("0123456789ABCDEF"
def get_number():
while True:
try:
number = int(input("Number: "))
return number
except ValueError:
print("Not a number, try again")
if __name__ == "__main__":
number = get_number()
convert = Converter(number)
convert.to_bin()
convert.to_oct()
convert.to_hex()
#Todo this
#base = get_number()
convert.to_base("01234")
@webpigeon
Copy link

!/usr/bin/env python

def numtobin(num):
if type(num) is not int:
return

div = num
binary = ""

while (div != 0):
    (div, mod) = divmod(div, 2)
    if mod == 1:
        binary += "1"
    else:
        binary += "0"

return binary

if name == "main":
try:
num = int(raw_input("enter number: "))
print ( numtobin(num) )
except:
print ("Not a valid number")

@webpigeon
Copy link

Well damnit,

I put it in an enclosure and made it prompt the user for input (have it in my ~/scripts/tools folder ^.^)

#!/usr/bin/env python

def numtobin(num):
    if type(num) is not int:
        return

    div = num
    binary = ""

    while (div != 0):
        (div, mod) = divmod(div, 2)
        if mod == 1:
            binary += "1"
        else:
            binary += "0"

    return binary


if __name__ == "__main__":
    try:
        num = int(raw_input("enter number: "))
        print ( numtobin(num) )
    except:
        print ("Not a valid number")

@SuborbitalPigeon
Copy link
Author

This was just a silly thing I did in an empty MM113 (Applications) class

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment