我找到了解决方案,下面是我所做的解释。
我需要执行以下操作:
1)确定二进制值的长度:
2) 确定大于长度输出的2 的最小幂,然后在二进制输出的左边加0,直到长度与返回的2 的最小幂值匹配。
上面的一些解决方案可以在这个优秀的线程上找到 Python 中大于 n 的 2 的最小幂。以下是我尝试过的三个功能:
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