Python使用和逻辑对两个二进制数产生一个新的二进制数

2024-09-29 17:51:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用AND函数从另外两个二进制数生成一个新的二进制数。但是,我一直得到000000000000作为输出。有人能发现我的代码哪里出错了吗

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 = '')

Tags: inipformatforinputreturnaddress二进制
1条回答
网友
1楼 · 发布于 2024-09-29 17:51:07

你在比较一个字符串和一个数字。将最后一行改为例如:

print(andop(int(x),int(y)),end = '')

另外,请注意二进制“and”操作是内置的。您可以轻松地以更清晰的方式重新编写此程序:

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'))

最后,要处理IP地址,有一个ipaddress模块:https://docs.python.org/3/library/ipaddress.html

相关问题 更多 >

    热门问题