0

How can I use python .format() to take an unsigned binary integer and output an ip address/netmask? For example,

print("Netmask {...} ".format('10001000100010001000100010001000'))
10001000.10001000.10001000.10001000
5
  • socket.inet_ntoa(struct.pack('!L', int('10001000100010001000100010001000', 2))) Commented Jun 5, 2019 at 19:35
  • @JohnnyMopp Interesting, but I don't want to import Socket module just for this. Commented Jun 5, 2019 at 19:37
  • 1
    Is '{}.{}.{}.{}'.format(s[:8], s[8:18], s[16:24], s[24:]) what you want? Commented Jun 5, 2019 at 20:03
  • @Goyo Yes! How could I be so blind?! Commented Jun 5, 2019 at 20:04
  • @Goyo If you make your comment an answer I will accept it Commented Jun 5, 2019 at 20:10

1 Answer 1

2

You can use your input, bitshift it after masking and put it back together:

number = int('10001000100010001000100010001000',2)

one = number & 0xff
two = (number & 0xff00) >> 8
three = (number & 0xff0000) >> 16
four = (number & 0xff000000) >> 24

print(f"{four}.{three}.{two}.{one}")
print(f"{four:b}.{three:b}.{two:b}.{one:b}")

Output

136.136.136.136                       # as normal int

10001000.10001000.10001000.10001000   # as binary int

You can use "{:b}.{:b}.{:b}.{:b}".format(four,three,two,one) instead of f-strings if you are below 3.6.


Disclaimer: this uses Python int to binary string? applied to some binary bitshiftiness:

  10001000100010001000100010001000  # your number  
& 11111111000000000000000000000000  # 0xff000000
= 10001000000000000000000000000000  # then >> 24
                          10001000 

  10001000100010001000100010001000  # your number  
& 00000000111111110000000000000000  # 0xff0000
= 00000000100010000000000000000000  # then >> 16
                  0000000010001000  # etc. 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.