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
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Timothy Pulliam
  • 132
  • 1
  • 9
  • 25

1 Answers1

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. 
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69