Python 各進制間的轉換(轉)


轉載自:http://blog.chinaunix.net/uid-21516619-id-1824975.html

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



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM