Python进制转换

#python 2.6以后内置函数

#10进制转为2进制
>>> bin(10)
'0b1010'

#2进制转为10进制
>>> int("1001",2)
9


#10进制转为16进制
>>> hex(10)
'0xa'

#16进制到10进制
>>> int('ff'16)
255

>>> int('0xab'16)
171

#十进制转为八进制
>>print("%o" % 10)
>>12


#16进制到2进制
>>> bin(0xa)
'0b1010'
>>>


#10进制到8进制
>>> oct(8)
'010' 

#2进制到16进制
>>> hex(0b1001)
'0x9'


#IP地址之间的转换
import socket
import time
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))

#时间戳格式化
def l2t (lint):
    return time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(lint))

posted @ 2012-03-14 17:53  Goodpy  阅读(172)  评论(0)    收藏  举报