Python 各进制间的转换
2016-05-06 11:40
701 查看
From: http://blog.chinaunix.net/uid-21516619-id-1824975.html
#python 2.6以后内置函数
#10进制转为2进制
>>> bin(10)
'0b1010'
#10进制转为16进制
>>> hex(10)
'0xa'
#10进制到8进制
>>> oct(8)
'010'
通过格式化输出:
#十进制转为八进制
>>print("%o" % 10)
>>12
#2进制转为10进制
>>> int("1001",2)
9
#16进制到10进制
>>> int('ff', 16)
255
>>> int('0xab', 16)
171
#8进制到10进制
>>> int("010",8)
8
#16进制到2进制
>>> bin(0xa)
'0b1010'
#2进制到16进制
>>> hex(0b1001)
'0x9'
#IP地址之间的转换
import socket
import struct
def ip2hex (ip):
return hex(struct.unpack("!I", socket.inet_aton(ip))[0])
def ip2long (ip):
return struct.unpack("!I", socket.inet_aton(ip))[0]
def long2ip (lint):
return socket.inet_ntoa(struct.pack("!I", lint))
#python 2.6以后内置函数
#10进制转为2进制
>>> bin(10)
'0b1010'
#10进制转为16进制
>>> hex(10)
'0xa'
#10进制到8进制
>>> oct(8)
'010'
通过格式化输出:
#十进制转为八进制
>>print("%o" % 10)
>>12
#2进制转为10进制
>>> int("1001",2)
9
#16进制到10进制
>>> int('ff', 16)
255
>>> int('0xab', 16)
171
#8进制到10进制
>>> int("010",8)
8
#16进制到2进制
>>> bin(0xa)
'0b1010'
#2进制到16进制
>>> hex(0b1001)
'0x9'
#IP地址之间的转换
import socket
import struct
def ip2hex (ip):
return hex(struct.unpack("!I", socket.inet_aton(ip))[0])
def ip2long (ip):
return struct.unpack("!I", socket.inet_aton(ip))[0]
def long2ip (lint):
return socket.inet_ntoa(struct.pack("!I", lint))
相关文章推荐
- Python 类与元类的深度挖掘 I【经验】
- Python 迭代器工具包【推荐】
- pythonwin-win32gui 窗口查找和遍历
- python对文件的操作
- python3 字符编码问题原理简介
- run SVN commands using python
- Python-安装feedparser
- Python -- 冒泡排序算法
- Python yield 使用浅析
- Python 主要模块和常用方法简览
- python 安装 mysql-python遇到的问题
- python 内建函数basestring笔记
- Python使用UUID库生成唯一ID
- 杂记_一些关于python代码风格汇总_不断更新
- hash加密 python
- 基于python sqlite3将KDD-99数据集插入数据库中
- Python selenium爬虫
- 使用python将KDD-99中的文本替换为数值形式
- 基于python一个分发小脚本
- python str和repr的区别