将ip转换为二进制

时间:2015-03-07 19:27:33

标签: python python-3.x binary ip

我正在尝试将4个输入的IP地址八位字节转换为二进制形式。这只是将第一个八位字节转换为8位形式的代码的一部分。 ' OC'是八位字节 - 当我开始工作时,我会修复变量名。

remainder = 0

bits = (128,64,32,16,8,4,2,1)

binary = [0,0,0,0,0,0,0,0]

oc = int(input("Enter oc1: "))
if oc > 256:
    print("Only 256 or less")

if oc > bits[0] or oc == bits[0]:
    binary[0] = 1
    remainder = remainder + oc - bits[0]
    print(binary)
    print(remainder)
elif oc < bits[0]:
    binary[0] = 0
    print(binary)

if remainder > bits[1] or remainder == bits[1]:
    binary[1] = 1
    remainder = remainder - bits[1]
    print(binary)
    print(remainder)
elif oc < bits[1]:
    binary[1] = 0
    print(binary)

if remainder > bits[2] or oc == bits[2]:
    binary[2] = 1
    remainder = remainder - bits[2]
    print(binary)
    print(remainder)
elif oc < bits[2]:
    binary[2] = 0
    print(binary)

当我输入128或更大的八位字节时,我得到一个成功的输出。

例如:进入&#39; 192&#39;将显示&#39; 1,1,0,0,0,0,0,0&#39;但是任何低于128的输出都是零。

我确信,我也可以使用循环,但不知道如何。

3 个答案:

答案 0 :(得分:2)

这对你有用吗?

oc = int(input("Enter oc1: "))
if oc > 256:
    print("Only 256 or less")
else:
    binary = bin(oc)[2:]

bin()将一个整数转换为二进制,并使用[2:]附加项删除前导的'0b'否则会得到。

如果你想确保你有8个字符,前导零,你可以使用zfill()。作为另一个附属物,zfill(n)将添加前导零,直到你的字符串长n个字符。

binary = bin(oc)[2:].zfill(8)

答案 1 :(得分:1)

将IPv4地址转换为二进制:

Treat Input links as OR

输入:

library(leaflet)
library(dplyr)

td <- read.csv("treedata.csv", header = TRUE)
m <- leaflet(td) %>% addTiles('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', 
                              attribution='Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> &mdash; Map data &copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>')
m %>% addCircles(~Longitude, ~Latitude, popup=paste("Name:", td$CommonName), weight = 3, radius=3, 
                 color="#ffa500", stroke = TRUE, fillOpacity = 0.8)

输出:

ip=raw_input("Enter the ip address\n") #input the ipv4 address
ips=ip.split('.') #split by '.'

for i in ips:  #ips is a list of octets,
 ##we parse through the list to convert each of these to binary
    print(format(int(i),'08b')) #Use format '08b' to add leading '0' to form '8' digits of binary 'b'

答案 2 :(得分:0)

@Tom给出的解决方案似乎最合适。但是如果你想学习将十进制转换成二进制的基础学校数学,那么就有一个解决方案。

import sys

string = "127.0.0.1"
oc = string.split(".")
for i in range(0, 4) :
   num = int(oc[i]) 
   j = 0;
   remlist = []
   while num > 0 :
       rem = num % 2
       j = j + 1
       remlist.append(rem)
       num = num / 2

   for x in range(j, 8) :
       remlist.append(0)    
   for element in reversed(remlist) :  
       print element,
   if i < 3 :
       print ".",