进制之间互相转换代码

# --coding:utf8--
#
file:baseconvert.py

BASE2 
=   " 01 "
BASE10 
=   " 0123456789 "
BASE16 
=   " 0123456789ABCDEF "
BASE62 
=   " ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz "
BASE36 
=   " 0123456789abcdefghijklmnopqrstuvwxyz "

def  baseconvert(number,fromdigits,todigits):
    
"""  converts a "number" between two bases of arbitrary digits

    The input number is assumed to be a string of digits from the
    fromdigits string (which is in order of smallest to largest
    digit). The return value is a string of elements from todigits
    (ordered in the same way). The input and output bases are
    determined from the lengths of the digit strings. Negative 
    signs are passed through.

    decimal to binary
    >>> baseconvert(555,BASE10,BASE2)
    '1000101011'

    binary to decimal
    >>> baseconvert('1000101011',BASE2,BASE10)
    '555'

    integer interpreted as binary and converted to decimal (!)
    >>> baseconvert(1000101011,BASE2,BASE10)
    '555'

    base10 to base4
    >>> baseconvert(99,BASE10,"0123")
    '1203'

    base4 to base5 (with alphabetic digits)
    >>> baseconvert(1203,"0123","abcde")
    'dee'

    base5, alpha digits back to base 10
    >>> baseconvert('dee',"abcde",BASE10)
    '99'

    decimal to a base that uses A-Z0-9a-z for its digits
    >>> baseconvert(257938572394L,BASE10,BASE62)
    'E78Lxik'

    ..convert back
    >>> baseconvert('E78Lxik',BASE62,BASE10)
    '257938572394'

    binary to a base with words for digits (the function cannot convert this back)
    >>> baseconvert('1101',BASE2,('Zero','One'))
    'OneOneZeroOne'

    
"""

    
if  str(number)[0] == ' - ' :
        number 
=  str(number)[ 1 :]
        neg
= 1
    
else :
        neg
= 0

    
#  make an integer out of the number
    x = long(0)
    
for  digit  in  str(number):
       x 
=  x * len(fromdigits)  +  fromdigits.index(digit)
    
    
#  create the result in base 'len(todigits)'
    res = ""
    
while  x > 0:
        digit 
=  x  %  len(todigits)
        res 
=  todigits[digit]  +  res
        x 
/=  len(todigits)
    
if  neg:
        res 
=   " - " + res

    
return  res
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值