【问题标题】:Converting either a Decimal or Binary value to Binary signed 2's complement in Python在 Python 中将十进制或二进制值转换为二进制有符号 2 的补码
【发布时间】:2020-04-29 11:51:57
【问题描述】:

我无法在 Python 中实现以下任一目标:

  1. 将 Decimal 值转换为二进制有符号 2 的补码。例子:

    40975 = 00000000000000001010000000001111
    
    275 = 0000000100010011
    
  2. 将二进制值转换为二进制有符号 2 的补码。例子:

    1010000000001111 = 00000000000000001010000000001111
    
    100010011 = 0000000100010011
    

有谁知道在 Python 中实现这一目标的最简单方法?

【问题讨论】:

  • 我认为这些适合你的问题stackoverflow.com/questions/10080559/…
  • 谢谢,但我认为该帖子对我没有帮助。它似乎更多地谈论获得十六进制表示法。我可能遗漏了一些东西,但我无法从该帖子中找到我需要的东西:/

标签: python binary decimal complement


【解决方案1】:

我找到了解决方案,下面是我所做的解释。

我需要做以下事情:

1) 确定二进制值的长度:

2) 确定大于输出长度的2的最小幂,然后在二进制输出的左边加0,直到长度与返回的2的最小幂值匹配。

上面的一些解决方案可以在这个优秀的线程Find the smallest power of 2 greater than n in Python 上找到。以下是我尝试过的三个功能:

len_1 = 16
len_2 = 9

def next_power_of_2_ver_1(x):  
    return 1 if x == 0 else 2**(x).bit_length()

Output:
32
16


def next_power_of_2_ver_2(x):
    return 1 if x == 0 else 2**math.ceil(math.log2(x + 1))

Output:
32
16


def next_power_of_2_ver_3(x):
    return 1<<(x).bit_length()

Output:
32
16

我已经确定了以下解决方案:

def next_power_of_2_ver_3(x):
    return 1<<(x).bit_length()

虽然这是我拥有的较大代码的一部分,但实现我需要的操作如下:

import math

# this function returns the smallest power of 2 greater than the binary output length so that we may get Binary signed 2's complement
def next_power_of_2(x): 
    return 1<<(x).bit_length()

decimal_value = "40975"

# convert the decimal value to binary format and remove the '0b' prefix
binary_value = bin(int(decimal_value))[2:] 
Output: 1010000000001111

# determine the length of the binary value
binary_value_len = len(binary_value) 
Output: 16

# use function 'next_power_of_2' to return the smallest power of 2 greater than the binary output length
power_of_2_binary_value_len = next_power_of_2(binary_value_len) 
Output: 32

# determine the amount of '0's we need to add to the binary result
calc_leading_0 = power_of_2_binary_value_len - binary_value_len
Output: 16

# adds the leading zeros thus completing the binary signed 2's complement formula
binary_signed_2s_binary_value = (binary_value).zfill(binary_value_len + calc_leading_0) 
Output: 00000000000000001010000000001111

【讨论】:

    猜你喜欢
    • 2014-05-21
    • 2011-09-03
    • 2013-09-28
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 2012-10-05
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多