Advertisement
6E697465737472796B72

ip 2 Decimal

Feb 23rd, 2025
32
0
6 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.02 KB | None | 0 0
  1. def ip_to_decimal():
  2.     # Ask the user for an IP address
  3.     ip_address = input("Enter an IP address (e.g., 192.168.0.1): ").strip()
  4.    
  5.     # Split the IP address into its four parts
  6.     parts = ip_address.split(".")
  7.     if len(parts) != 4:
  8.         print("Invalid IP address format.")
  9.         return
  10.  
  11.     binary_str = ""
  12.     for part in parts:
  13.         try:
  14.             # Convert each octet to an integer and validate its range
  15.             num = int(part)
  16.             if not (0 <= num <= 255):
  17.                 print("Each octet must be between 0 and 255.")
  18.                 return
  19.             # Convert the integer to an 8-bit binary string and concatenate
  20.             binary_str += format(num, '08b')
  21.         except ValueError:
  22.             print("Invalid input. Please enter numbers only.")
  23.             return
  24.  
  25.     # Convert the 32-bit binary string to a decimal integer
  26.     decimal_value = int(binary_str, 2)
  27.     print("The decimal representation is:", decimal_value)
  28.  
  29. if __name__ == "__main__":
  30.     ip_to_decimal()
  31.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement