Python格式无符号二进制整数到IP地址
如何使用python.format()获取无符号二进制整数并输出ip地址/网络掩码?比如说,Python格式无符号二进制整数到IP地址,python,python-3.x,string,Python,Python 3.x,String,如何使用python.format()获取无符号二进制整数并输出ip地址/网络掩码?比如说, print("Netmask {...} ".format('10001000100010001000100010001000')) 10001000.10001000.10001000.10001000 您可以使用输入,在屏蔽后对其进行位移位,然后将其重新组合在一起: number = int('10001000100010001000100010001000',2) one = number &
print("Netmask {...} ".format('10001000100010001000100010001000'))
10001000.10001000.10001000.10001000
您可以使用输入,在屏蔽后对其进行位移位,然后将其重新组合在一起:
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}.”格式(四,三,二,一)
而不是f-strings
免责声明:此用法适用于某些二进制位移位:
10001000100010001000100010001000 # your number
& 11111111000000000000000000000000 # 0xff000000
= 10001000000000000000000000000000 # then >> 24
10001000
10001000100010001000100010001000 # your number
& 00000000111111110000000000000000 # 0xff0000
= 00000000100010000000000000000000 # then >> 16
0000000010001000 # etc.
您可以使用输入,在屏蔽后对其进行位移位,然后将其重新组合在一起:
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}.”格式(四,三,二,一)
而不是f-strings
免责声明:此用法适用于某些二进制位移位:
10001000100010001000100010001000 # your number
& 11111111000000000000000000000000 # 0xff000000
= 10001000000000000000000000000000 # then >> 24
10001000
10001000100010001000100010001000 # your number
& 00000000111111110000000000000000 # 0xff0000
= 00000000100010000000000000000000 # then >> 16
0000000010001000 # etc.
socket.inet_ntoa(struct.pack('!L',int('10001000',2))
@johnymapp很有趣,但我不想仅仅为了这个而导入套接字模块。是'{}.{}.{}.{}。格式(s[:8],s[8:18],s[16:24],s[24:])
你想要什么?@Goyo是的!我怎么会这么瞎@Goyo如果你的评论是一个答案,我会接受它socket.inet_ntoa(struct.pack('!L',int('10001000',2))
@johnymopp有趣,但我不想仅仅为了这个而导入socket模块。是'{}.{}.{}.{}。格式(s[:8],s[8:18],s[16:24]:
你想要什么?@Goyo Yes!我怎么会这么瞎@高雄如果你的评论是我的回答,我会接受的