Python 各进制间的转换

来源:互联网 发布:js cinfirm 编辑:程序博客网 时间:2024/06/03 22:40

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))

0 0
原创粉丝点击