2013-11-02 121 views
0

我需要一個將用戶輸入的IPv4地址轉換爲二進制和基地址10的程序。事情是這樣的:將點十進制IP地址轉換爲二進制(Python)

input: 142.55.33.1 
output (base 10): [2385977601] 
output (base 2): [10001110 00110111 00100001 00000001] 

到目前爲止,我已經成功地將其轉換成一個base10地址,但我似乎無法得到解決的基礎問題2:

#!/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) 

任何幫助將不勝感激。謝謝。

回答

4

使用format

>>> 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' 
+0

非常感謝!這非常有幫助! – user1819786

1

使用str.format

>>> ip_address = '142.55.33.1' 
>>> ['{:08b}'.format(int(n)) for n in ip_address.split('.')] 
['10001110', '00110111', '00100001', '00000001'] 
>>> ' '.join('{:08b}'.format(int(n)) for n in ip_address.split('.')) 
'10001110 00110111 00100001 00000001' 
+0

['{:08b}'.format(int(n))for ip_address.split('。')] < - 你能解釋一下這裏發生了什麼嗎? – user1819786

+0

@ user1819786,'[... for item in seq]'被稱爲[** list comprehension **](http://docs.python.org/2/tutorial/datastructures.html#list-comprehensions)。 – falsetru

+0

'str.format'用於對數字進行二進制表示。例如'':{:08b}'。format(3)'產生'00000011'。請參閱[格式字符串語法](http://docs.python.org/2/library/string.html#formatstrings)。 – falsetru

相關問題