Wednesday, March 9, 2022

IP Address to Number Python Codewars

Task:

An IPv4 address is a 32-bit number that identifies a device on the internet.

While computers read and write IP addresses as a 32-bit number, we prefer to read them in dotted-decimal notation, which is basically the number split into 4 chunks of 8 bits, converted to decimal, and delmited by a dot.

In this kata, you will create the function ipToNum that takes an ip address and converts it to a number, as well as the function numToIp that takes a number and converts it to an IP address string. Input will always be valid.

Conversion Example

//original IP address
192.168.1.1

//breaks down into 4 binary octets
11000000 . 10101000 . 00000001 . 00000001

//which are merged together (unsigned 32-bit binary)
11000000101010000000000100000001

//and finally converted to base 10
3232235777
ipToNum
ipToNum('192.168.1.1') //returns 3232235777
ipToNum('10.0.0.0') //returns 167772160
ipToNum('176.16.0.1') //returns 2953838593
numToIp
numToIp(3232235777) //returns '192.168.1.1'
numToIp(167772160) //returns '10.0.0.0'
numToIp(2953838593) //returns '176.16.0.1'

Solution:


def ip_to_num(ip):
    b = ''
    for i in ip.split('.'):
        b += format(int(i), "08b")
    return int(b,2)

def num_to_ip(num):
    binary = bin(num).lstrip('0b').zfill(32)
    ip=[]
    for i in range(0, len(binary), 8):
        octet = binary[i:i+8]
        ip.append(str(int(str(octet),2)))
    return '.'.join((ip))

print(ip_to_num('176.16.0.1'))
print(num_to_ip(2953838593))

Training on IP Address to Number | Codewars



Related Posts


No comments :

Post a Comment