#二进制转换成十进制
##v = "0b1111011"##print(type(v))##a = int(v,2)##print(type(a))##print(a)#十进制转换成二进制
##v = 18##v = bin(v)##print(v)#八进制转换为十进制
##v = "011"##print(int(v,8))#十进制转化为八进制
##v = 30##print(oct(v))##shi = oct(v)##print(int(shi,8))#十六进制转换为十进制
##v = "0x12"##print(int(v,16))#十进制转换为16进制
##v = 87##print(hex(v))##总结
##1.转换至二进制 用bin()函数##2.转换至八进制 用oct()函数##3.转换为十进制 用int(X,可选参数)加入可选参数来转换##4.转换为十六进制 用hex()函数##练习
##编写一个函数实现将IP地址转换成一个整数##如:10.3.9.12##10 XXXXXXXX##3 XXXXXXXX##9 XXXXXXXX##12 XXXXXXXX####再将上述二进制加起来计算十进制结果:##程序分析##1.接收输入内容或者获取本机ip## ##2.将输入内容进行转换## 1.用split()函数将IP地址分解## 2.将结果放进列表,并作出转换##3.叠加转化内容计算##4.输出结果####import socket
####from socket import gethostbyname_ex,gethostname####local_IP_list = gethostbyname_ex(gethostname())##print(local_IP_list)##local_IP = gethostbyname_ex(gethostname())[2]##print(type(local_IP))####for i in local_IP[0,2]:#### print(i)##print(local_IP)##
##ip = "1.1.1.1"
##########def func(ip):## a = ip.split(".")#### print(a)## s = ''## L = []## for i in a:#### print(i)#### print(type(i))## i = bin(int(i))[2:]#### print(i)#### print(type(i))## i = i.rjust(8,"0")## print(i)## print(type(i))## L.append(i)## s = s.join(L)## return print(int(s,2))####func(ip)
#!/usr/bin/env python
# -*- coding: utf-8 -*-# 2/10/16 base trans. wrote by srcdog on 20th, April, 2009# ld elements in base 2, 10, 16.import os,sys
# global definition
# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]# bin2dec
# 二进制 to 十进制: int(str,n=10) def bin2dec(string_num): return str(int(string_num, 2))# hex2dec
# 十六进制 to 十进制def hex2dec(string_num): return str(int(string_num.upper(), 16))# dec2bin
# 十进制 to 二进制: bin() def dec2bin(string_num): num = int(string_num) mid = [] while True: if num == 0: break num,rem = divmod(num, 2) mid.append(base[rem])return ''.join([str(x) for x in mid[::-1]])
# dec2hex
# 十进制 to 八进制: oct() # 十进制 to 十六进制: hex() def dec2hex(string_num): num = int(string_num) mid = [] while True: if num == 0: break num,rem = divmod(num, 16) mid.append(base[rem])return ''.join([str(x) for x in mid[::-1]])
# hex2tobin
# 十六进制 to 二进制: bin(int(str,16)) def hex2bin(string_num): return dec2bin(hex2dec(string_num.upper()))# bin2hex
# 二进制 to 十六进制: hex(int(str,2)) def bin2hex(string_num): return dec2hex(bin2dec(string_num))