IP地址十进制与二进制的转换

一、IPv4

十进制->二进制

def get_bin_v4(prefix):
    ip = prefix.split('/')[0]
    mask = prefix.split('/')[1]
    bin_all = (''.join([bin(int(x) + 256)[3:] for x in ip.split('.')]))
    return bin_all


prefix_v4 = '192.168.1.0/24'
bin_mask_1 = get_bin_v4(prefix_v4)
print(bin_mask_1)

输出如下:

11000000101010000000000100000000

二进制->十进制

def get_decimal_v4(bin_all):
    """
    :param bin_all: str
    :return:
    """
    decimal_all = ''
    bin_all = list(bin_all)
    for i in range(0, len(bin_all)-1, 8):  # 0, 1, 2, 3
        decimal = int(bin_all[i]) * pow(2, 7) + int(bin_all[i+1]) * pow(2, 6) + int(bin_all[i+2]) * pow(2, 5) + int(bin_all[i+3]) * pow(2, 4) + \
                + int(bin_all[i+4]) * pow(2, 3) + int(bin_all[i+5]) * pow(2, 2) + int(bin_all[i+6]) * pow(2, 1) + int(bin_all[i+7]) * pow(2, 0)
        decimal_all += str(decimal)
        if i!= 24:
            decimal_all += '.'
    return decimal_all


    bin_v4 = '11000000101010000000000100000000'
    decimal_all = get_decimal_v4(bin_v4)
    print(decimal_all)

输出如下:

192.168.1.0

二、IPv6

十进制->二进制

def get_bin_v6(prefix):
    bin_all = ''
    ip = prefix.split('/')[0]
    mask = prefix.split('/')[1]
    part_list = ip.split(':')

    miss_part = 8 - len(part_list)

    for part in part_list:
        if part != '':
            bin_all += bin(int(part, 16))[2:].zfill(16)
        else:
            for i in range(miss_part + 1):
                bin_all += bin(int('0', 16))[2:].zfill(16)
    return bin_all


prefix_v6 = '2001:1248:43bc::/48'
bin_mask_2 = get_bin_v6(prefix_v6)
print(bin_mask_2)

输出如下:

00100000000000010001001001001000010000111011110000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

二进制->十进制

参考IPv4的转化方法。

你可能感兴趣的:(网络基础,ip)