2016-05-13 42 views
0

因此,我試圖用一些二進制字符串讀取文件,即: 10000010 00000000 0000 **** ********。該腳本將*的轉換爲0和1,所以會有兩個二進制字符串是這樣的:Python將二進制字符串轉換爲虛線格式的IP地址

10000010 00000000 00000000 00000000 10000010和00000000 00001111 11111111

腳本將它們轉換爲IP地址,所以在這個例子中,我的腳本應該返回130.0.0.0和130.0.15.255

這是到目前爲止我的代碼:

def main(): 
    text=open('filename', 'r').readlines() 
    for line in text: 
     words = line.split(" ") 
     words_2=list(words) 
     for char in words: 
      low_range=char.replace('*','0') 
      conversion=str(int(low_range, 2)) 
      decimal='.'.join(map(str,conversion)) 
      print(decimal) 
     for char in words_2: 
      high_range=char.replace('*','1') 
      conversion_2=str(int(high_range, 2)) 
      decimal='.'.join(map(str,conversion_2)) 
      print(decimal) 
main() 

當我運行我的代碼,它打印出:

1.3.0 
0 
0 
0 
1.3.0 
0 
6.3 
2.5.5 
1.3.0 
0 
6.4 
0 
1.3.0 
0 
9.5 
2.5.5 
1.3.0 
0 
1.2.8 
0 
1.3.0 
0 
1.9.1 
2.5.5 
1.3.0 
0 
1.3.0 
0 
1.9.2 
0 
1.3.0 
0 
2.5.5 
2.5.5 

當我真的希望它打印出來:

130.0.0.0 
130.0.63.255 
130.0.64.0 
130.0.95.255 
130.0.128.0 
130.0.191.255 
130.0.192.0 
130.0.255.255 

任何人都可以幫助解釋什麼,我做錯了什麼?

回答

0

你是加盟字節的十進制表示的字母,而你應該加入字節本身。

decimal='.'.join(map(str,conversion)) 

另外你在自己的行打印IP的每個字節

print(decimal) 

以下是我會寫循環:

for line in text: 
    words = line.split(" ") 

    for bit in '01':   
     ip = [] 
     for word in words: 
      byte=word.replace('*', bit) 
      ip.append(str(int(byte, 2))) 
     print '.'.join(ip) 
+0

非常感謝!完美的作品。假設我想在IP地址與0之間設置查找範圍,並將IP地址設爲1,例如在130.0.0.0-130.0.63.255之間。這會像添加一個「for i in range(ip)」循環一樣簡單嗎? – ojbomb227

0

你可以用簡單的格式:

"%d.%d.%d.%d" % (0b10000010, 0b00000000, 0b00000000, 0b00000000) 
# '130.0.0.0' 

從字符串讀取的二進制數(比如"10000010")使用方法:

int("10000010", 2) 
# 130 

如果你想與我建議使用ipaddress IP地址工作:

>>> import ipaddress 
>>> ipaddress.IPv4Address("%d.%d.%d.%d" % (0b10000010, 0b00000000, 0b00000000, 0b00000000)) 
IPv4Address('130.0.0.0') 

但是,它不可用在Python 2.x中

0

您的示例將輸入按空格分隔到變量words。然後你迭代單詞,將它們轉換爲int並將其轉換爲字符串變量conversion。這一切都有道理。

的問題是以下行:

decimal='.'.join(map(str,conversion)) 

當獲得的首次值爲'130'執行。 map調用是不必要的,它只是將conversion變成字符串列表:['1', '3', '0']。然後,您將這些字符串與.一起加入,以便您在輸出中看到1.3.0。請注意,即使您刪除map,也會得到相同的結果,因爲join只會迭代字符串中的字符。

而不是迭代字符只是將每個單詞與int轉換,就像你正在做的,並將它們收集到一個列表。然後將它們轉換爲map或列表理解的字符串,最後將它們與.一起加入。

這裏有一個簡單的例子,做它:

with open('test.txt') as text: 
    for line in text: 
     print '.'.join(str(int(x, 2)) for x in line.split()) 
相關問題