Pythonで16ビット整数の補数加算を実装しましたが、それを行うためのより良い方法があるかどうかを確認しようとしています.
# This function returns a string of the bits (exactly 16 bits)
# for the number (in base 10 passed to it)
def get_bits(some_num):
binar = bin(some_num)[2::]
zeroes = 16 - len(binar)
padding = zeroes*"0"
binar = padding + binar
return binar
# This function adds the numbers, and handles the carry over
# from the most significant bit
def add_bits(num1, num2):
result = bin(int(num1,2) + int(num2,2))[2::]
# There is no carryover
if len(result) <= 16 :
result = get_bits(int(result,2))
# There is carryover
else :
result = result[1::]
one = '0000000000000001'
result = bin(int(result,2) + int(one,2))[2::]
result = get_bits(int(result,2))
return result
そして今、それを実行する例は次のようになります:
print add_bits("1010001111101001", "1000000110110101")
戻り値 :
0010010110011111
結果に関して安全に書いたものはありますか(その部分は些細なことなので、ここでは否定しませんでした。中間のステップにもっと興味があります)?それを行うためのより良いPythonicの方法はありますか? 助けてくれてありがとう。