2

I am trying to convert 4 entered octets of an IP address into their binary form. This is only part of the code for converting the first octet into its 8 bit form. 'oc' is octet - I will fix variable names when I get this working.

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)

When I enter 128 or greater as the octet I get a successful output.

E.g.: Entering '192' will display '1,1,0,0,0,0,0,0' but anything below 128 and the output is all zeros.

I am sure, I could use a loop for most of this as well but do not know how.

2
  • 1
    Have you looked at ipaddress? Commented Mar 7, 2015 at 19:37
  • i dont see anything about converting an ip to its binary form.. just trying to create this program for a the convenience it'll bring when converting ip to binary @PeterWood Commented Mar 7, 2015 at 19:46

3 Answers 3

2

Will this work for you?

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

bin() converts an integer to binary, and using the [2:] appendage drops the leading '0b' you would otherwise get.

If you want to ensure that you have 8 characters, with leading zeros, you can use zfill(). As another appendage, zfill(n) will add leading zeros until your string is n characters long.

binary = bin(oc)[2:].zfill(8)
Sign up to request clarification or add additional context in comments.

2 Comments

being new to python, this method took me by surprise! is there any way to keep the most significant zeros, seeing as there should be 8 bits when converting ip to binary? @Tom thanks!
Yup, use zfill(). I edited my answer to include it. You should also probably consider including a if oc < 0: print('Non-negatives only'), lest the [2:] will not work perfectly.
1

Convert a IPv4 address to binary :

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'

Input :

192.95.01.56

Output:

11000000
01011111
00000001
00111000

Comments

0

The solution given by @Tom seems most appropriate. But if you want to go to basic school mathematics of converting decimal to binary, one solution is this.

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 ".", 

9 Comments

python loops confuse me.. what exactly does the 'i' in 'for i in range(0, 4):' mean?
python loops confuse me.. what exactly does the 'i' in 'for i in range(0, 4):' mean? @mayankTUM
The function string.split(".") parses the string into an array of strings of size 4. range(0,4) returns a list of integers [0,1,2,3] and 'i' is simply the iterator that loops through all these values. Similar to "for(i = 0; i<4; i++)" in c or java.
so the string.split(".") produces the 4 numbers in string without the "."? and if i had this code: train = 1,2,3 for name in train: value = name*10 print(value) what does 'name' stand for in 'for name'? this is an example i saw a while back @mayankTUM
if I understood your question correctly, name will take the value 1 first, then 2 and so on. You will get 10,20,30 as the output.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.