Convert CIDR notation in Python

In Python, it seems that you can do it by using a module called netaddr, I only needed CIDR conversion, so I wrote it myself.

>>> import socket, struct
>>> def cidr2mask(len):
...     return socket.inet_ntoa(struct.pack('!L', 0xffffffff ^ ((1 << 32-len)-1)))
... 
>>> cidr2mask(8)
'255.0.0.0'
>>> cidr2mask(16)
'255.255.0.0'
>>> cidr2mask(24)
'255.255.255.0'
>>> cidr2mask(20)
'255.255.240.0'

There seems to be a more elegant way of writing.

Recommended Posts

Convert CIDR notation in Python
Class notation in Python
Convert exponential notation float to str in Python
Included notation in Python function arguments
Convert markdown to PDF in Python
Display LaTeX notation formulas in Python, matplotlib
Quadtree in Python --2
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Convert psd file to png in Python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Convert from Markdown to HTML in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
Convert absolute URLs to relative URLs in Python
LiNGAM in Python
Flatten in python
flatten in python
Convert FBX files to ASCII <-> BINARY in Python
Convert PDFs to images in bulk with Python
Convert cubic mesh code to WKT in Python
Sorted list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python