Cau*_*chy 0 python ones-complement
我在 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
Run Code Online (Sandbox Code Playgroud)
现在运行它的一个例子是:
print add_bits("1010001111101001", "1000000110110101")
Run Code Online (Sandbox Code Playgroud)
返回:
0010010110011111
Run Code Online (Sandbox Code Playgroud)
就结果而言,所写的内容是否安全(请注意,我在这里没有做任何否定,因为那部分是微不足道的,我对中间步骤更感兴趣)?有没有更好的pythonic方法来做到这一点?谢谢你的帮助。
在字符串和整数之间来回转换以进行数学运算是低效的。用整数进行数学运算并使用格式来显示二进制:
MOD = 1 << 16
def ones_comp_add16(num1,num2):
result = num1 + num2
return result if result < MOD else (result+1) % MOD
n1 = 0b1010001111101001
n2 = 0b1000000110110101
result = ones_comp_add16(n1,n2)
print('''\
{:016b}
+ {:016b}
------------------
{:016b}'''.format(n1,n2,result))
Run Code Online (Sandbox Code Playgroud)
输出:
1010001111101001
+ 1000000110110101
------------------
0010010110011111
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3071 次 |
| 最近记录: |