我一直在Python中做二進制算術。對我來說這似乎很笨拙,可能是因爲有更好的方法。提供的示例代碼創建一個二進制數字列表,創建反向列表並創建絕對差異。任何建議更好的技術將不勝感激。Python二進制算術
for (i, j, k, n, m) in [(i, j, k, n, m)for i in range(2) for j in range(2) \
for k in range(2)for n in range(2) for m in range(2)]:
s = [i, j, k, n, m] # binary sequence
r = s[::-1] # reversed sequence
sbin = '0b' # create binary number as string
rbin = '0b'
for a in range(5):
sbin += str(s[a])
rbin += str(r[a])
sbb = int(sbin,2) # create binary number
rbb = int(rbin,2)
v = abs(sbb - rbb) # take absolute difference as integers
dif = bin(v) # convert back to binary
print(sbin, rbin, dif, v)
拼寫錯誤的二進制標題對不起,可能限制迴應 – Graybits