Python內建進位制轉換函式(實現16進位制和ASCII轉換)
阿新 • • 發佈:2018-10-31
在進行wireshark抓包時你會發現底端視窗報文內容左邊是十六進位制數字,右邊是每兩個十六進位制轉換的ASCII字元,這裡使用Python程式碼實現一個十六進位制和ASCII的轉換方法。
hex()
轉換一個整數物件為十六進位制的字串
>>> hex(16)
'0x10'
>>> hex(18)
'0x12'
>>> hex(32)
'0x20'
>>>
oct()
轉換一個整數物件為八進位制的字串
>>> oct(8) '0o10' >>> oct(166) '0o246' >>>
bin()
轉換一個整數物件為二進位制字串
>>> bin(10)
'0b1010'
>>> bin(255)
'0b11111111'
>>>
chr()
轉換一個[0, 255]之間的整數為對應的ASCII字元
>>> chr(65)
'A'
>>> chr(67)
'C'
>>> chr(90)
'Z'
>>> chr(97)
'a'
>>>
ord()
將一個ASCII字元轉換為對應整數
>>> ord('A') 65 >>> ord('z') 122 >>>
寫一個ASCII和十六進位制轉換器
上面我們知道hex()可以將一個10進位制整數轉換為16進位制數。而16進位制轉換為10進位制數可以用int('0x10', 16) 或者int('10', 16)
16進位制轉10進位制 >>> int('10', 16) 16 >>> int('0x10', 16) 16 8進位制轉10進位制 >>> int('0o10', 8) 8 >>> int('10', 8) 8 2進位制轉10進位制 >>> int('0b1010', 2) 10 >>> int('1010', 2) 10
程式碼如下:
class Converter():
@staticmethod
def to_ascii(h):
list_s = []
for i in range(0, len(h), 2):
list_s.append(chr(int(h[i:i+2], 16)))
return ''.join(list_s)
@staticmethod
def to_hex(s):
list_h = []
for c in s:
list_h.append(str(hex(ord(c))[2:]))
return ''.join(list_h)
print(Converter.to_hex("Hello World!"))
print(Converter.to_ascii("48656c6c6f20576f726c6421"))
# 等寬為2的16進位制字串列表也可以如下表示
import textwrap
s = "48656c6c6f20576f726c6421"
res = textwrap.fill(s, width=2)
print(res.split()) #['48', '65', '6c', '6c', '6f', '20', '57', '6f', '72', '6c', '64', '21']
生成隨機4位數字+字母的驗證碼
可以利用random模組加上chr函式實現隨機驗證碼生成。
import random
def verfi_code(n):
res_li = list()
for i in range(n):
char = random.choice([chr(random.randint(65, 90)), chr(
random.randint(97, 122)), str(random.randint(0, 9))])
res_li.append(char)
return ''.join(res_li)
print(verfi_code(6))