[英]Python Using AND logic on two binary numbers to produce a new binary number
我正在嘗試使用 AND function 從其他兩個二進制數生成一個新的二進制數。 但是,我不斷得到 000000000000 作為 output。 誰能發現我的代碼哪里出錯了?
def andop(x,y):
if x == 1 and y == 1:
return 1
else:
return 0
v = input("Enter IP address: ")
ip = v.split(".")
b1 = format(int(ip[0]),'08b')
x = input("Enter submask address: ")
subm = x.split(".")
bi1 = format(int(subm[0]),'08b')
for x in b1:
for y in bi1:
print(andop(x,y),end = '')
您正在將字符串與數字進行比較。 將最后一行更改為例如:
print(andop(int(x),int(y)),end = '')
另外,請注意二進制“與”操作是內置的。 你可以用更清晰的方式輕松地重寫這個程序:
v = input("Enter IP address: ")
ip = v.split(".")
b1 = int(ip[0])
x = input("Enter submask address: ")
subm = x.split(".")
bi1 = int(subm[0])
print(format(b1 & bi1, 'b'))
Finally, to work with IP addresses, there's an ipaddress
module: https://docs.python.org/3/library/ipaddress.html .
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.