从二进制到基数48的转换

问题描述 投票:0回答:1

[我创建了一个将二进制作为字符串的函数,然后将其转换为base48,它适用于大多数测试用例,但是当我通过它运行“ 1010000001101101011000000100000001000101111010000101101010110110000001100110”时]

import math
def Binary2Octoquadragesimal(n):

     octdict = {"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","16":"g","17":"h","18":"i","19":"j","20":"k","21":"l","22":"m","23":"n","24":"o","25":"p","26":"q","27":"r","28":"s","29":"t","30":"u","31":"v","32":"w","33":"x","34":"y","35":"z","36":"A","37":"B","38":"C","39":"D","40":"E","41":"F","42":"G","43":"H","44":"I","45":"J","46":"K","47":"L",}


     ans = []

     if n == "":
         return ""

     i = int(n,2)

     if i == 0:
         return "0"

     while i > 0:
         ans.append(octdict[str(i%48)])
         i = math.floor(i/48)
     ans.reverse()
     print (ans)
     return ("".join(ans))

返回错误的值,我仔细检查了一下代码,在这个特定的测试案例中,我的函数似乎返回Dragonfly00w6而不是Dragonfly2026,为什么在这种情况下只会发生这种情况,而在其他情况下不会发生?以及我该如何补救

我创建了一个将二进制作为字符串的函数,然后将其转换为base48,它适用于大多数测试用例,但是当我运行“ ...

python python-3.x loops dictionary base
1个回答
0
投票

您的问题是浮点数错误。该数字太大,无法用python float表示。它仅适用于ints,因为python ints具有任意精度。

© www.soinside.com 2019 - 2024. All rights reserved.