Python将二进制字符串转换为虚线表示法中的IP地址 [英] Python Convert Binary String to IP Address in Dotted Notation

查看:268
本文介绍了Python将二进制字符串转换为虚线表示法中的IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图用一些二进制字符串读取一个文件,即:
10000010 00000000 0000 **** ********。该脚本将*转换为0和1,因此将有两个二进制字符串如下所示:

So I'm trying to read in a file with some binary strings, i.e: 10000010 00000000 0000**** ********. The script will convert the *'s to both 0 and 1, so there will be two binary strings that look like this:

10000010 00000000 00000000 00000000和10000010 00000000 00001111 11111111 。

10000010 00000000 00000000 00000000 and 10000010 00000000 00001111 11111111.

然后脚本会将它们转换为ip地址,所以在这个例子中,我的脚本应该返回130.0.0.0和130.0.15.255

Then the script will convert them to ip addresses, so in this example, my script should return 130.0.0.0 and 130.0.15.255

这是我到目前为止的代码:

This is my code so far:

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()

我运行我的代码,打印出来:

When I run my code, it prints out:

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 

当我真的想要打印出来时:

When I really want it to print out:

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  

任何人都可以帮忙解释我做错了什么吗?

Can anyone help explain what I am doing wrong?

推荐答案

您正在加入字节十进制表示的字母,而您应该自己加入字节。

You are joining the letters of byte's decimal representation, while you should join the bytes themselves.

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

您还可以在自己的行上打印ip的每个字节

Also you print each byte of an ip on its own line

print(decimal)

以下是我编写循环的方法:

Here's how I'd write the loop:

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)

这篇关于Python将二进制字符串转换为虚线表示法中的IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆