-1

Python で次のいずれかを達成するのに問題があります。

  1. Decimal 値を 2 進数の符号付き 2 の補数に変換します。例:

    40975 = 00000000000000001010000000001111
    
    275 = 0000000100010011
    
  2. バイナリ値をバイナリ符号付き 2 の補数に変換します。例:

    1010000000001111 = 00000000000000001010000000001111
    
    100010011 = 0000000100010011
    

Pythonでこれを達成する最も簡単な方法を知っている人はいますか?

4

1 に答える 1

0

私は解決策を見つけました。以下は私がしたことの説明です。

私は次のことをする必要がありました:

1) バイナリ値の長さを決定します。

2) 長さ出力よりも大きい最小の 2 のべき乗を決定し、最小の 2 のべき乗値を返す長さが一致するまでバイナリ出力の左側に 0 を追加します。

上記の解決策のいくつかは、この優れたスレッドFind the least power of 2 greater than n in Python で見つけることができます。私が試した3つの機能は次のとおりです。

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
于 2020-01-13T15:02:24.237 に答える