Convert a given IP address to binary using Python

Solved
```python
def ip_vers_ip_binaire(ip):
# Séparer l'adresse IP en octets
octets = ip.split('.')
# Convertir chaque octet en binaire, en supprimant le '0b' et en complétant avec des zéros à gauche
binaire = ''.join(format(int(octet), '08b') for octet in octets)
return binaire

# Exemple d'utilisation
print(ip_vers_ip_binaire('192.168.0.1')) # Sortie : '11000000101010000000000000000001'
```

7 answers

  1. Hello,

    In my opinion, you should start by splitting the address 192.168 ... into an array of 4 pieces that are each 8 bits
    then you write the 4 numbers one after the other without anything in between

    So you need the function that splits with a separator which is the dot "." and that gives you the 4 numbers.

    Then a print with a binary format in 8 bits.
    In my opinion, all of this is in the python documentation.
    Take a look :)

    https://overapi.com/python
    Hints:
    there are functions such as:
    str.split()
    int()
    bin()

    --
    PC seven,
    Firefox, Ball mouse... :-b
    1
    1. Thank you very much for your guidance. I'll get to work on it, and if I find anything, I'll send it to you. Thanks again!
      0
    2. @LilouxI found it :)

      Instead of bin(), there's format(thing, stuff)
      1
    3. @magoueroah yes, that's right, thank you
      0
  2. Contributor
    0
    1. Hello,

      I'm not looking for the right answer, just some help.
      I've already started with this:

      def convertir(T): """ T is an array of integers, where the elements are 0 or 1 and represent an integer written in binary. Returns the positive integer whose binary representation is given by the array T """ n = len(T) dec_int = 0 # Initialization of the decimal integer whose binary representation we have for k in range(n): dec_int = dec_int + T[k] * 2 ** (n - 1 - k) return dec_int 


      Except that if I convert it to
      str
      , the calculation does not work and I get an error.
      0
    2. @yg_be
       def convert(T) """ T is an array of integers, where the elements are 0 or 1 and represent an integer written in binary. Returns the positive integer whose binary representation is given by the array T """ n = len(T) dec_int = 0 # initialization of the decimal integer whose binary representation we have for k in range(n): dec_int=dec_int+T[k]*2**(n-1-k) return dec_int 
      0
    3. @yg_beMy function works well but I believe it doesn't help me at all because it converts binary to decimal and I need to do the opposite.
      From what I understand, I need to take my data like '192', convert it to binary by adding zeros if necessary, and then "stick" the data together to create a long binary corresponding to each part.
      0
    4. Contributor
      @LilouxI think so too.
      1
  3. Moderator
    Hello,

    Regarding message #4, some clarifications.
    • You indeed need to split your IPv4 address into 4 integers. Each of these integers ranges from 0 to 255 and therefore fits into one byte (that is, 4 integers of 8 bits each, so an IPv4 corresponds to 4 * 8 = 32 bits). For this, you can use the method
      split()
      .


    Example:

    (x, y, z, t) = adresse_ip.split(".")
    • You can convert a string that contains an integer (e.g.,
      "192"
      ) to an integer using the function
      int()
      .


    Example:

    i = int("192")
    • For each of these 4 integers, you can represent it in binary using the function
      bin()
      . Example:
      bin(192)
      . However, you will see that the returned string is prefixed with
      "0b"
      . If you want to remove this prefix, you just need to consider the binary representation obtained from the second character.


    Example:

    b = bin(192)[2:]
    • By concatenating these four strings, you will obtain the binary representation of your IP address.


    Good luck.
    0
    1. So, found it? :)

      --
      PC seven,
      Firefox,
      Ball mouse... :-b
      0
      1.  Yes! I've created several functions so that my main function (ip_vers_ip_binaire(ip)) isn't too large 

         def decimal_en_binaire(a): """a is a positive integer in base 10 Returns its value converted to base 2 as a string """ bin_a = str(a%2) # Initialization of the binary word a = a // 2 while a!=0 : bin_a = str(a % 2) + bin_a a = a//2 return bin_a def ip_vers_liste(ip): """ip is an ipv4 address of type str Returns the array of bytes (in decimal of type int) """ tab_str = ip.split('.') tab_int= [int(k) for k in tab_str] #creation of the array that converts tab_str(type str) to integer (type int) return tab_int def ip_vers_ip_binaire(ip): """ip is an ipv4 address of type str Returns the ip by converting the bytes to binary and without the separating dots. The returned ip is of type str """ ip =ip_vers_liste(ip) #transformation of a string into a list n = len(ip) binn1='' # binn1 is an empty string manque= '0' #manque is used to add 0s to reach 8 bits for each of the 4 parts of the IP binn= '0' for i in range(4): binn= decimal_en_binaire(ip[i]) if len(binn)!=8: binn = manque*(8-len(binn))+ binn binn1= binn1 + binn return binn1 
        0
        1. I had:

          addressIp = "192.168.0.1" # the address we want to process print(addressIp) # just for debugging def ipToBinary(addressIp): toto = addressIp.split('.') result = "" # init result to have string format for counter in toto: #print(counter) # just for debugging result = result+format(int(counter),'08b') print(result) return 0 #launch the action ipToBinary(addressIp) 

          --
          PC seven,
          Firefox,
          Mouse with ball... :-b
          0
          1. Ah yes, it is definitely shorter than mine and only requires one function. Well done and thank you!
            0
        2. Moderator
          Hello,

          You can make it shorter by using this trick:

          def ip_to_binary(ipv4): return "".join( "{0:08b}".format(int(n)) for n in ipv4.split(".") ) print(ip_to_binary("192.168.0.1"))


          Good luck
          0
          1. Bonjour mamie,

            can you explain the use of FOR in your example? I don't understand what the part in the join i.e.:
            "{0:08b}".format(int(n)) for n in ipv4.split(".")

            does in front of the for.
            For me, the for returns nothing since it's not followed by any instruction.
            And the Python 3.10.3 documentation states §8.3 for FOR:
            "for_stmt ::= "for" target_list "in" expression_list ":" suite
            ["else" ":" suite]"

            it seems that the ":" is not optional so I don't understand why this doesn't throw an error but let's assume. And we have nothing for suite so there's no action.

            If we simplify with
             n for n in ipv4.split(".")

            it works and outputs 19216801, makes sense.

            But how? Can you explain or send me to a section of the documentation that will help me understand?

            Thank you in advance.
            0
          2. Moderator
            @magoueroHello magouero,

            What's probably blocking you is that you don't yet know the syntax of the
            for
            loops used in list comprehensions.

            This syntax applies to a
            list
            , a
            tuple
            , a
            dict
            , a generator.

            To be precise, it is more about the syntax associated with a generator that is passed to the
            list
            ,
            tuple
            ,
            dict
            constructor.

            In the syntax you already know, the function I mentioned can be rewritten as:

            def ip_vers_ip_binaire(ipv4): ma_liste = list() for n in ipv4.split("."): ma_liste.append("{0:08b}".format(int(n))) return "".join(ma_liste)


            "{0:08b}".format(int(n))
            means "write the integer
            n
            in binary format in at most 8 characters by adding any missing leading 0s to obtain 8 characters". For more details, see this link.

            Good luck!
            1
          3. Moderator
            @magoueroBut damn, finding that in the documentation without knowing what it's called ...

            Yes, yes, I know, but you’re going to make me blush :D Well, to be honest, I don’t deserve any credit apart from knowing how to search properly ;-)

            Thanks Mamiemando.

            You're welcome, good luck :-)
            0