zoukankan      html  css  js  c++  java
  • python基础:5.请编写一个函数实现将IP地址转换成一个整数。

    如 10.3.9.12 转换规则为:
            10            00001010
    
         3            00000011

             9            00001001
    
        12            00001100

    再将以上二进制拼接起来计算十进制结果:00001010 00000011 00001001 00001100 = ?

     1 class Switch(object):
     2 
     3     def __init__(self, ip_str):
     4         self.ip_str = ip_str
     5 
     6     def ten_switch_two(self, num):
     7         demo = list()
     8         while num > 0:
     9             ret = num % 2
    10             demo.append(str(ret))
    11             num = num // 2
    12         temp = "".join((list(reversed(demo))))
    13         head_zero = "0"*(8-len(temp))
    14         ret = head_zero + temp
    15         return ret
    16 
    17     def two_switch_ten(self, num):
    18         # 字符串转列表
    19         num_list = list()
    20         for i in num:
    21             num_list.append(i)
    22         temp = 0
    23         s = len(num_list) - 1
    24         for i in num_list:
    25             temp += int(i) * 2 ** s
    26             s -= 1
    27         return temp
    28 
    29     def run(self):
    30         # 1.切割字符串
    31         part_list = self.ip_str.split(".")
    32         # 2.循环取出每个数字转成二进制数
    33         temp_str = ""
    34         for ip_part in part_list:
    35             temp_str += self.ten_switch_two(int(ip_part))
    36         ret = self.two_switch_ten(temp_str)
    37         print(ret)
  • 相关阅读:
    转战Python
    spark
    idea的配置
    19年春第十六周学习
    19年春第十五周学习
    个人作业-最长英语链
    rpm dpkg 用法比较
    foxmail 无法下载同步邮件 error:00000001:lib(0):func(0):reason(1)
    date命令详解
    用cron服务自动运行脚本
  • 原文地址:https://www.cnblogs.com/meloncodezhang/p/11281606.html
Copyright © 2011-2022 走看看