Question

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.

Was it helpful?

Solution

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'

OTHER TIPS

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'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top