enter = ('255.255.0.0')
def ff (s):
s = s.split('.')
B1 = str(bin(int(s[0])))
B2 = str(bin(int(s[1])))
B3 = str(bin(int(s[2])))
B4 = str(bin(int(s[3])))
s = B1[2:],B2[2:],B3[2:],B4[2:]
for i in s:
if len(i) < 8:
i = 8 - len(i)
r =i * '0'
return s
print(ff(enter))
上面的代码有什么问题?我需要输出应该像[11111111,11111111,00000000,0000000]
答案 0 :(得分:0)
Bazingaa指出了您的代码问题并提供了解决方案。这是解决问题的另一种方法:
def ff (s):
s = s.split('.')
s = [bin(int(x)) for x in s] # ['0b11111111', '0b11111111', '0b0', '0b0']
s = [x[2:] for x in s] # ['11111111', '11111111', '0', '0']
s = [x.zfill(8) for x in s] # ['11111111', '11111111', '00000000', '00000000']
return s
或者我们可以将这些行组合在一起:
def ip_to_binary(ip):
return [bin(int(x))[2:].zfill(8) for x in ip.split('.')]
注释
zfill
方法,它是字符串对象的一部分bin
返回一个字符串,因此我们无需调用str
将其再次转换为字符串ff
,s
等隐含名称... ...这样会使代码更难以理解enter = ('255.255.0.0')
与enter = '255.255.0.0'
相同答案 1 :(得分:-1)
你很近。问题是您在s
时没有为0
的值更新len(j) < 8
。
解决方法是将元组s
转换为列表,然后按如下所示更新0
的值。我已经评论了修改后的行。
enter = ('255.255.0.0')
def ff (s):
s = s.split('.')
B1 = str(bin(int(s[0])))
B2 = str(bin(int(s[1])))
B3 = str(bin(int(s[2])))
B4 = str(bin(int(s[3])))
s = B1[2:],B2[2:],B3[2:],B4[2:]
s = list(s) # Convert tuple to list
for i, j in enumerate(s): # Enumerate to access index for modifying
if len(j) < 8:
j = 8 - len(j)
s[i] = j * '0'
return s
print(ff(enter))
# ['11111111', '11111111', '0000000', '0000000']