Codewars:IPv4 to int32


Description :

Take the following IPv4 address: 128.32.10.1 This address has 4 octets where each octet is a single byte (or 8 bits).
  • 1st octet 128 has the binary representation: 10000000
  • 2nd octet 32 has the binary representation: 00100000
  • 3rd octet 10 has the binary representation: 00001010
  • 4th octet 1 has the binary representation: 00000001
So 128.32.10.1 == 10000000.00100000.00001010.00000001
Because the above IP address has 32 bits, we can represent it as the 32 bit number: 2149583361.
Write a function ip_to_int32(ip) ( JSipToInt32(ip) ) that takes an IPv4 address and returns a 32 bit number.

Example:

ip_to_int32("128.32.10.1") => 2149583361


Code:

def ip_to_int32(ip):
    octe=ip.split(".")
    sum=""
    n=0
    for bix in octe:
        bnr = bin(int(bix))[2:]
        x = bnr[::-1#this reverses an array
        while len(x) < 8:
            x += '0'
            bnr = x[::-1]
        sum=sum+str(bnr)
    for d in sum:
        n = n * 2 + int(d)
    return n


Explanation:

1.split the text using "."

2.convert each octent into 8 bits such that we get total 32 bits

3.combine all 4 octents

4.convert the combined octents into decimal value

5.return the output