0

I made a programme to convert IP address to dotted decimal format, but am experiencing a weird bug.

Code:

import math

def ip_format(ip_address):
    ip_address = int(ip_address)
    dotted_decimal = ""
    while ip_address>=1:
        remaining = math.floor(ip_address % 100000000)
        ip_address = math.floor(ip_address / 100000000)
        
        power = 0
        final_remaining_value = 0
        while remaining >= 1 :
            value = math.floor(remaining % 10)
            remaining = math.floor(remaining / 10)
            final_remaining_value += (2 ** power) * value
            power += 1
        
        print(final_remaining_value)
        dotted_decimal = f'.{final_remaining_value}' + dotted_decimal
        print(dotted_decimal)
    return dotted_decimal[1:]

print(ip_format('00000011100000001111111111111111')) prints 3.128.256.255.

print(ip_format('100000001111111111111111')) prints 128.255.255.

I am unsure what is causing my 255 to change to 256 when the only change is adding an additional 8 digits to the string, which should not affect the processing of the 8 digits for that relevant 255 value.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Bob Tan
  • 103
  • 6
  • The ``/`` division uses *floating point* arithmetic in contrast to the ``//`` division using precise integer arithmetic. Adding 8 digits changes the precision of the floating point arithmetic. – MisterMiyagi Jan 17 '22 at 14:18

1 Answers1

1

You can use ipaddress.ip_address() if you wish. No need to reinvent the wheel:

>>> import ipaddress
>>> ipaddress.ip_address(int('00000011100000001111111111111111', base=2))
IPv4Address('3.128.255.255')
Bharel
  • 23,672
  • 5
  • 40
  • 80
  • 1
    Could benefit from URL to docs https://docs.python.org/3/library/ipaddress.html#ipaddress.IPv4Address – JackLeo Jan 17 '22 at 14:26