如何使用python .format()来获取无符号二进制整数并输出IP地址/网络掩码?例如,
print("Netmask {...} ".format('10001000100010001000100010001000'))
10001000.10001000.10001000.10001000
答案 0 :(得分:2)
您可以使用您的输入,在掩蔽后对它进行位移位并将其放回一起:
number = int('10001000100010001000100010001000',2)
one = number & 0xff
two = (number & 0xff00) >> 8
three = (number & 0xff0000) >> 16
four = (number & 0xff000000) >> 24
print(f"{four}.{three}.{two}.{one}")
print(f"{four:b}.{three:b}.{two:b}.{one:b}")
输出
136.136.136.136 # as normal int
10001000.10001000.10001000.10001000 # as binary int
如果您低于3.6,则可以使用"{:b}.{:b}.{:b}.{:b}".format(four,three,two,one)
代替f-strings
。
免责声明:这将Python int to binary string?应用于某些二进制位移位:
10001000100010001000100010001000 # your number
& 11111111000000000000000000000000 # 0xff000000
= 10001000000000000000000000000000 # then >> 24
10001000
10001000100010001000100010001000 # your number
& 00000000111111110000000000000000 # 0xff0000
= 00000000100010000000000000000000 # then >> 16
0000000010001000 # etc.