algorithm-in-python/math/numWeight/convertWeight.py

54 lines
1.3 KiB
Python
Raw Normal View History

2018-10-02 21:24:06 +08:00
''' mbinary
#########################################################################
# File : num_weight.py
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-10-02 21:24:06 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-05-19 21:36
# Description:
#########################################################################
'''
2020-04-15 12:28:20 +08:00
def covert(s, basefrom=10, baseto=2):
return d2n(n2d(s, basefrom), baseto)
def n2d(s, base=16):
2018-10-02 21:24:06 +08:00
''' num of base_n(n<36) to decimal'''
2020-04-15 12:28:20 +08:00
dic = {chr(i+ord('0')): i for i in range(10)}
s = s.upper()
if base > 10:
dic.update({chr(i+ord('A')): i+10 for i in range(26)})
# if base in [16,8,2] :
2018-10-02 21:24:06 +08:00
# p=max(map(s.find,'OBX'))
# s=s[p+1:] #remove prefix of hex or bin or oct
2020-04-15 12:28:20 +08:00
rst = 0
2018-10-02 21:24:06 +08:00
for i in s:
2020-04-15 12:28:20 +08:00
rst = dic[i]+rst*base
2018-10-02 21:24:06 +08:00
return rst
2020-04-15 12:28:20 +08:00
def d2n(n, base=16):
2018-10-02 21:24:06 +08:00
''' num of base_n(n<36) to decimal'''
2020-04-15 12:28:20 +08:00
dic = {i: chr(i+ord('0')) for i in range(10)}
if base > 10:
dic.update({i+10: chr(i+ord('A')) for i in range(26)})
rst = []
while n != 0:
i = int(n/base)
2018-10-02 21:24:06 +08:00
rst.append(dic[n-i*base])
2020-04-15 12:28:20 +08:00
n = i
2018-10-02 21:24:06 +08:00
return ''.join(rst[::-1])
'''
>>> n2d(str(d2n(4001)))
4001
>>> d2n(n2d(str(4001)),2)
'100000000000001'
>>> covert('4001',16,2)
'100000000000001'
'''