RE: Converting an IP to Decimal (Python 3.3) 05-13-2014, 01:36 AM
#2
(05-13-2014, 01:02 AM).Shebang Wrote: Honestly, I don't know if I'm using the best practices here for parsing the input, but here it is:
Code:try: x = list(map(int, input("Enter an IP Address: ").split("."))) if len(x) == 4: total = 0 for i in range(0, 4): total += x[i] << (8 * (3 - i)) print("IP to decimal: " + str(total)) else: print("Invalid IP address.") except ValueError: print("Invalid IP Address.")
This just converts an IP address to it's decimal counterpart (which can be interpreted by things like Chrome), knowing the following pattern:
IP Address: 10.9.8.7
Decimal = (10 << 24) + (9 << 16) + (8 << 8) + 7 = (10 * 2^24) + (9 * 2^16) + (8 * 2^8) + 7 = 168364039
You did a pretty good job. I won't say much is wrong with it, but I will say that it can be shortened.
Spoiler: Shortened version
Code:
x,total = list(map(int, input('IP: ').split('.'))),0;
if len(x) == 4:
for i in range(0,4): total += x[i] << (8 * (3 - i)); print(str(total));![[Image: BXqGARG.png]](https://i.imgur.com/BXqGARG.png)








![[+]](https://sinister.ly/images/modern/collapse_collapsed.png)