Python中的网络掩码前缀和点分十进制格式转换

问题描述 投票:0回答:1

在我提出这个问题之前,我在这里找到一个相关的帖子:how to convert a bit mask prefix into a dotted-decimal notation

但它的PHP知识。

经过努力,我现在可以将点分十进制转换为前缀:

e_mask = lambda mask: sum(bin(int(i)).count('1') \
                                 for i in mask.split('.'))

print(e_mask('255.255.255.0'))  # there print `24`

但我不知道如何使用24转换为255.255.255.0

python algorithm
1个回答
1
投票

作为@DanD。指出,您可以轻松地将位计数转换为前缀掩码。然后将掩码转换为四个单独的字节然后转换为字符串相当容易:

def bits_to_mask(n):
    if n < 0 or n > 32:
        raise ValueError('Bit count must be between 0 and 32')
    mask = (~((1 << (32 - n)) - 1)) & 0xFFFFFFFF
    return '.'.join(map(str, ((mask >> (8 * i)) & 0xFF for i in range(3, -1, -1))))

[Qazxswpoi]

© www.soinside.com 2019 - 2024. All rights reserved.