python进制转换——py学习笔记

#python内置函数

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