Python 各進制間的轉換(轉)

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

python 2.6之後內置函數

#10進制轉爲2進制
>>> bin(10)
'0b1010'

#2進制轉爲10進制
>>> int("1001",2)
9python

#10進制轉爲16進制
>>> hex(10)
'0xa'

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

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

#十進制轉爲八進制
>>print("%o" % 10)
>>12


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

socket

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


相關文章
相關標籤/搜索