0

I need a program that would convert a user inputted IPv4 Address to a Binary and Base 10 Address. Something like this:

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

So far I have managed to convert it into a base10 address but I can't seem to get around the base 2 problem:

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

Any help would be greatly appreciated. Thank you.

2 Answers 2

4

Use format:

>>> text = '142.55.33.1'
>>> ' ' .join(format(int(x), '08b') for x in text.split('.'))
'10001110 00110111 00100001 00000001'

In case if you want a list:

>>> [format(int(x), '08b') for x in text.split('.')]
['10001110', '00110111', '00100001', '00000001']

Here format converts an integer to its binary string representation:

>>> format(8, 'b')
'1000'
>>> format(8, '08b')  #with padding
'00001000'
Sign up to request clarification or add additional context in comments.

Comments

1

Using 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'

3 Comments

['{:08b}'.format(int(n)) for n in ip_address.split('.')] <-- could you kindly explain what's going on here?
@user1819786, [... for item in seq] is called list comprehension.
str.format is used to make a binary representation of the number. For example '{:08b}'.format(3) yields 00000011. See Format String Syntax.

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.