Я нашел решение, ниже приведено объяснение того, что я сделал.
Мне нужно было сделать следующее:
1) Определить длину двоичного значения:
2) Определите наименьшую степень 2, превышающую выходную длину, затем добавьте 0 слева от двоичного выхода, пока длина не совпадет с возвращаемой наименьшей степенью значения 2.
Некоторые решения для вышеупомянутого можно найти в этой превосходной теме Найти наименьшую степень 2 больше, чем n в 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