Python格式的无符号二进制整数到IP地址

2024-04-24 09:54:00 发布

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

如何使用python.format()获取无符号二进制整数并输出ip地址/网络掩码?例如

print("Netmask {...} ".format('10001000100010001000100010001000'))
10001000.10001000.10001000.10001000

Tags: ip网络format地址二进制符号整数netmask
1条回答
网友
1楼 · 发布于 2024-04-24 09:54:00

您可以使用您的输入,在屏蔽后对其进行位移,然后将其重新组合在一起:

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. 

相关问题 更多 >