zoukankan      html  css  js  c++  java
  • python 十进制转换成任意进制

    记得大学时代,参加学校举行的编程大赛,其中有道题是:

    编写一函数,实现十进制转换成十六进制。

    看起来非常简单的一道题,最后竟然没有实现,想想都觉得惭愧啊,回去网上一搜,那是相当的easy的事情;时隔五六年了,工作中一直是用java,最近学习python,所以突然想到这个问题,就用python来实现这道题。下面使用两种方法分别实现:

    一、循环

    def decimalToNBaseByNormal(decimalVar, base):
        tempList = []
        temp = decimalVar
        i = 0
        while (temp > 0):
            ord = temp % base
            if (ord > 9): #如果余数大于9,则以字母的形式表示
                ord = chr(65 + (ord - 10))   #把数字转换成字符
            tempList.append(ord)
            temp = int(temp / base)
            i = i + 1
        tempList.reverse();
        #print(tempList)
        binary = ""
        for j in range(len(tempList)):
            binary = binary + str(tempList[j]);
        print("the decimal is: %d and after convering by %d base is %s"%(decimalVar, base, binary))

    里面要注意的一点就是,当余数大于9时,要转换成字符表示;用循环的方法实现,思路非常清晰,至于转换算法这里就不多介绍,可以看参考[1];在该实现过程中碰到的问题是,怎么把数字转换成字符;当然首先是ascii对应表,转换方法如下:

    ord = chr(65 + (ord - 10))

    其中,ord为余数,转换后就对应ascii从A开始的字符,python 3.3中可以使用chr函数直接转换成字符

    二、递归

    def decToNBaseByRecursion(dec, base):
        if (dec == 0):
            return
        decToNBaseByRecursion(int(dec/base), base)
        ord = dec % base
        if (ord > 9):
            ord = chr(65 + (ord - 10))
        sys.stdout.write(str(ord))

    递归方法,实现使得代码非常简洁,但理解起来不是那么简单;递归实现过程中,碰到一个输出问题,python 3.3中,函数print默认自动换行,网上后面加逗号的方法,试了无效,所以直接使用stdout输出,这就要在使用import sys。

    主代码:

    import sys
    def main():
        decimal = eval(input("please input the decimal for converting binary: "))
        base = eval(input("please input base: "))
        decimalToNBaseByNormal(decimal, base)
        decToNBaseByRecursion(decimal, base)

    工具:PyScripter 

    python版本 3.3

    上面的链接是code.google,不翻是上不去的,我朝”伟大的杰作“啊!

    python刚入门,只考虑运行结果,没有考虑任何性能问题,有不正的地方,请指正!

    完整代码

    当然python里面有更简单的函数直接输出:

    二进制  bin()   

    八进制  oct()

    十六进制  hex()

    未完待续:任意进制转换成十进制

    转载请注明出处
  • 相关阅读:
    oracle 数据库服务名怎么查
    vmware vsphere 6.5
    vSphere虚拟化之ESXi的安装及部署
    ArcMap中无法添加ArcGIS Online底图的诊断方法
    ArcGIS中字段计算器(高级计算VBScript、Python)
    Bad habits : Putting NOLOCK everywhere
    Understanding the Impact of NOLOCK and WITH NOLOCK Table Hints in SQL Server
    with(nolock) or (nolock)
    What is “with (nolock)” in SQL Server?
    Changing SQL Server Collation After Installation
  • 原文地址:https://www.cnblogs.com/successjerry/p/4401428.html
Copyright © 2011-2022 走看看