Conversion.py which takes a decimal number as an input, and returns its representation in a given base as a string.

# conversion.py which takes a decimal number as an input, and returns its representation in a given base as a string (i.e. binary, octal, or hexadecimal string). The function uses a look-up table (dictionary) to map decimal integers to digits in the targeted base

lookUp = {0 : '0', 1 : '1', 2 : '2', 3 : '3', 4 :'4', 5 : '5', 6 : '6', 7 : '7', 8 : '8', 9 : '9', 10 : 'A', 11 : 'B', 12 :
'C', 13 : 'D', 14 : 'E', 15 : 'F'}

def dec_to_bin(x):
    return (bin(x))

def dec_to_hex(x):
    return (hex(x))

def dec_to_oct(x):
    return (oct(x))   




def decimalToRep(decNum,typeVal):
    if typeVal==2:
        string=str(decNum)
        st=list(string)
        t=[]
        b=''
        for i in st:
            for k,v in lookUp.items():
                if i==v:
                    t.append(v)
         
        for r in t:
            b+=((r))
   
        print(dec_to_bin(int(b)))

       

    elif typeVal==8:
        string=str(decNum)
        st=list(string)
        t=[]
        b=''
        for i in st:
            for k,v in lookUp.items():
                if i==v:
                    t.append(v)

        for r in t:
            b+=((r))
 
        print(dec_to_oct(int(b)))
         
       

       
    elif typeVal==16:
        string=str(decNum)
        st=list(string)
        print(st)
        t=[]
        b=''
        for i in st:
            for k,v in lookUp.items():
                if i==v:
                    t.append(v)
         
        for r in t:
            b+=((r))
 
        print(dec_to_hex(int(b)))


       
    else: 
        string=str(decNum)
        st=list(string)
        t=[]
        b=''
        for i in st:
            for k,v in lookUp.items():
                if i==v:
                    t.append(v)
         
        for r in t:
            b+=((r))
        print(b)   


 


 
 
def main():
    decimalToRep(10,10)               
    decimalToRep(10,2)               
    decimalToRep(10,8)               
    decimalToRep(10,16)               
 
if __name__=="__main__":
    main()             # call main function







# print("{0:#b}".format(15))
# print(hex(78))
# '0b10110'
Print this post

Comments

Popular posts from this blog

write a program that takes as an input a text file. Your program should print all the unique words in the file in alphabetical order.

Perform an in-depth evaluation of the following websites: Website 1: http://jbhifi.com.au Website 2: https://www.amazon.com

Global Bikes INC(GBI) Software Requirements Specifications (SRS)