【问题标题】:Writing a function to convert Two's Compliment to Base 10 in Python在 Python 中编写一个将二进制补码转换为 Base 10 的函数
【发布时间】:2014-12-28 04:11:40
【问题描述】:

我的任务是编写一个函数,该函数在 Two's Compliment 系统中采用任意长度的二进制字符串,并返回以 10 为底的相应整数。我不能使用 for 或 while 循环,也不能使用 built在转换功能。我可以使用递归。

我编写了一个辅助函数,它获取二进制字符串中的第一个数字,并找到以 10 为底的值将添加到总和中,我已将其复制在下面。

def first(str):
    '''this program finds the value in base 10 of the 0th digit in a string of binary'''

    n=len(str)
    return int(str[0])*(2**(n-1))

我在处理负数以及整个函数的格式方面需要帮助。 谢谢!

【问题讨论】:

  • 这不是代码编写服务; 你的尝试在哪里,它到底有什么问题?
  • 这个问题似乎是题外话,因为它是一个“我可以冒犯密码”的问题

标签: python python-3.x binary converter twos-complement


【解决方案1】:
def bin(s):
    return 0 if not s else 2*bin(s[:-1]) + int(s[-1])

convert_2_to_decimal = lambda s: bin(s[1:]) - int(s[0])*2**(len(s)-1)

【讨论】:

    猜你喜欢
    • 2016-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多