【问题标题】:Convert negative integer to binary将负整数转换为二进制
【发布时间】:2017-07-13 12:41:41
【问题描述】:

我正在研究这个将整数转换为 32 位二进制的函数。它适用于正整数,但我无法弄清楚如何在负整数到二进制转换的函数中实现二进制补码。我目前正在取负整数的绝对值,将该值转换为二进制,然后翻转字符串中的二进制值。我只是不知道如何在我的代码中实现二进制补码。

这是我所拥有的:

def intToHexaBin(num):
    binnum=abs(num)
    symdict={10:"A",11:"B",12:"C",13:"D",14:"E",15:"F"}
    rlist=[]
    blist=[]
    while(binnum!=0):
        if (binnum%2==0):
            blist.append(str(0))
        else:

            blist.append(str(1))
        binnum//=2
    x = (''.join(blist[::-1]).zfill(32))
    if (num<0):
        '''
        I got as far as reversing the binary values for
        converting a negative number to binary
        '''
        for index, value in enumerate(blist):
            blist[index] = '0'
            if value == '0':
                blist[index] = '1'
            elif value == '1':
                blist[index] = '0'
        #not sure how to implement two's complement from here

    return x

print(intToHexaBin(-12))

我试图避免使用内置的 python 函数,因为这个函数是我学习如何进行各种转换的练习。这是一项正在进行的工作。

【问题讨论】:

  • 你知道有一个名为bin()的内置函数,对吧?
  • 我知道 bin()。我很欣赏这个提示,但我试图在没有内置插件的情况下做到这一点,所以我可以学习。
  • int 8/16/32/64 与浮点数/负数?需要阅读更多IEEE

标签: python binary twos-complement


【解决方案1】:

好吧,在反转位后,您获得了 1 补码。要获得 2 补码,您必须“加 1”。所以你需要实现加法:

def add_a_bit(num_repr):
    for i in range(len(num_repr)):
        if num_repr[i] == '0':
            # 0+1 = 1
            num_repr[i] = '1'
            break
        # 1+1 = 0
        num_repr[i] = '0'
    return num_repr

所以在将blist 中的位反转后,调用add_a_bit(blist)

最后我会写一些类似的东西:

def int_to_bin(num):
    num_repr = []
    pos_num = abs(num)
    while pos_num:
        if pos_num % 2 == 0:
            num_repr.append('0')
        else:
            num_repr.append('1')
        pos_num //= 2
    if num < 0:
        num_repr = add_a_bit(invert_bits(num_repr))
    return ''.join(reversed(num_repr))


def invert_bits(num_repr):
    for value in num_repr:
        yield '0' if value == '1' else '1'

这似乎有效:

In [7]: int_to_bin(17), bin(17)
Out[7]: ('10001', '0b10001')

0除外:

In [8]: int_to_bin(0), bin(0)
Out[8]: ('', '0b0')

我会让你找到解决这个小错误的方法。

【讨论】:

  • 谢谢,我现在就去看看。
【解决方案2】:

我看到的最简单的解决方案如下:

def intToHexaBin(num):
    if num < 0:
        return '-' + intToHexaBin(-num)
    # continue code here

return 语句退出代码,忽略后面可能出现的任何内容,因此在将负值传递给函数的情况下,它会简单地将 - 添加到转换后的肯定答案之前。

【讨论】:

    猜你喜欢
    • 2018-10-10
    • 2012-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-31
    • 2012-04-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多