Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/unity3d/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将点十进制IP地址转换为二进制(Python)_Python_Binary_Ip_Ip Address_Data Conversion - Fatal编程技术网

将点十进制IP地址转换为二进制(Python)

将点十进制IP地址转换为二进制(Python),python,binary,ip,ip-address,data-conversion,Python,Binary,Ip,Ip Address,Data Conversion,我需要一个程序,将用户输入的IPv4地址转换为二进制和10进制地址。大概是这样的: input: 142.55.33.1 output (base 10): [2385977601] output (base 2): [10001110 00110111 00100001 00000001] 到目前为止,我已成功地将其转换为base10地址,但我似乎无法回避Base2问题: #!/usr/bin/python3 ip_address = input("Please enter a dot d

我需要一个程序,将用户输入的IPv4地址转换为二进制和10进制地址。大概是这样的:

input: 142.55.33.1
output (base 10): [2385977601]
output (base 2): [10001110 00110111 00100001 00000001]
到目前为止,我已成功地将其转换为base10地址,但我似乎无法回避Base2问题:

#!/usr/bin/python3

ip_address = input("Please enter a dot decimal IP Address: ")

#splits the user entered IP address on the dot
ListA = ip_address.split(".")
ListA = list(map(int, ListA))

ListA = ListA[0]*(256**3) + ListA[1]*(256**2) + ListA[2]*(256**1) + ListA[3]
print("The IP Address in base 10 is: " , ListA)

#attempt at binary conversion (failing)
#ListA = ListA[0]*(2**3) + ListA[1]*(2**2) + ListA[2]*(2**1) + ListA[3]
#print("The IP Address in base 2 is: " , ListA)
任何帮助都将不胜感激。多谢各位

使用:

使用:


使用
格式

>>> text = '142.55.33.1'
>>> ' ' .join(format(int(x), '08b') for x in text.split('.'))
'10001110 00110111 00100001 00000001'
如果需要列表,请执行以下操作:

>>> [format(int(x), '08b') for x in text.split('.')]
['10001110', '00110111', '00100001', '00000001']
此处格式将整数转换为其二进制字符串表示形式:

>>> format(8, 'b')
'1000'
>>> format(8, '08b')  #with padding
'00001000'

使用
格式

>>> text = '142.55.33.1'
>>> ' ' .join(format(int(x), '08b') for x in text.split('.'))
'10001110 00110111 00100001 00000001'
如果需要列表,请执行以下操作:

>>> [format(int(x), '08b') for x in text.split('.')]
['10001110', '00110111', '00100001', '00000001']
此处格式将整数转换为其二进制字符串表示形式:

>>> format(8, 'b')
'1000'
>>> format(8, '08b')  #with padding
'00001000'

['{:08b}.format(int(n))表示ip_地址中的n。split('.')]@user1819786,调用
[…表示seq中的项]
str.format
用于表示数字的二进制表示。例如,格式(3)产生
00000011
。请参见ip_address.split('.)]@user1819786中的n的格式(int(n)),
[…for item in seq]
str.format
用于对数字进行二进制表示。例如,格式(3)产生
00000011
。看见