Python內置進制轉換函數(實現16進制和ASCII轉換)


在進行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(object):
    @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))

其它進制轉換操作

把整數格式化為2位的16進制字符串,高位用零占位
>>> '{:02x}'.format(9)
>>> '09'

把整數格式化為2位的16進制字符串,高位用空占位
>>> '{:2x}'.format(9)
>>> ' 9'

把整數格式化為2位的16進制字符串
>>> '{:x}'.format(9)
>>> '9'

把整數格式化為2位的8進制字符串,高位用空占位
>>> '{:2o}'.format(9)
>>> '11'

把整數格式化為2位的8進制數字符串,高位用空占位
>>> '{:2o}'.format(6)
>>> ' 6'

把整數格式化為2位的8進制字符串,高位用零占位
>>> '{:02o}'.format(6)
>>> '06'

把整數格式化為8位的2進制字符串,高位用零占位
>>> '{:08b}'.format(73)
>>> '01001001'

把整數格式化為2進制字符串
>>> '{:b}'.format(73)
>>> '1001001'

把整數格式化為8位的2進制字符串,高位用空占位
>>> '{:8b}'.format(73)
>>> ' 1001001'

程序猿(二進制)的浪漫

哈哈聽說過程序猿的浪漫么,下面將ASCII字符'I love you'轉換為二進制,請將這些二進制發給你喜歡的人吧,看看who understands you

def asi_to_bin(s):
    list_h = []
    for c in s:
        list_h.append('{:08b}'.format(ord(c)))	# 每一個都限制為8位二進制(0-255)字符串
    return ' '.join(list_h)

print(asi_to_bin("I love you"))

# 01001001001000000110110001101111011101100110010100100000011110010110111101110101
# 01001001 00100000 01101100 01101111 01110110 01100101 00100000 01111001 01101111 01110101

python實現IP地址轉換為32位二進制

#!/usr/bin/env python
# -*- coding:utf-8 -*-


class IpAddrConverter(object):

    def __init__(self, ip_addr):
        self.ip_addr = ip_addr

    @staticmethod
    def _get_bin(target):
        if not target.isdigit():
            raise Exception('bad ip address')
        target = int(target)
        assert target < 256, 'bad ip address'
        res = ''
        temp = target
        for t in range(8):
            a, b = divmod(temp, 2)
            temp = a
            res += str(b)
            if temp == 0:
                res += '0' * (7 - t)
                break
        return res[::-1]

    def to_32_bin(self):
        temp_list = self.ip_addr.split('.')
        assert len(temp_list) == 4, 'bad ip address'
        return ''.join(list(map(self._get_bin, temp_list)))


if __name__ == '__main__':
    ip = IpAddrConverter("192.168.25.68")
    print(ip.to_32_bin())

python 判斷兩個ip地址是否屬於同一子網

"""
判斷兩個IP是否屬於同一子網, 需要判斷網絡地址是否相同
網絡地址:IP地址的二進制與子網掩碼的二進制地址邏輯“與”得到
主機地址: IP地址的二進制與子網掩碼的二進制取反地址邏輯“與”得到
"""


class IpAddrConverter(object):

    def __init__(self, ip_addr, net_mask):
        self.ip_addr = ip_addr
        self.net_mask = net_mask

    @staticmethod
    def _get_bin(target):
        if not target.isdigit():
            raise Exception('bad ip address')
        target = int(target)
        assert target < 256, 'bad ip address'
        res = ''
        temp = target
        for t in range(8):
            a, b = divmod(temp, 2)
            temp = a
            res += str(b)
            if temp == 0:
                res += '0' * (7 - t)
                break
        return res[::-1]

    def _to_32_bin(self, ip_address):
        temp_list = ip_address.split('.')
        assert len(temp_list) == 4, 'bad ip address'
        return ''.join(list(map(self._get_bin, temp_list)))

    @property
    def ip_32_bin(self):
        return self._to_32_bin(self.ip_addr)

    @property
    def mask_32_bin(self):
        return self._to_32_bin(self.net_mask)

    @property
    def net_address(self):
        ip_list = self.ip_addr.split('.')
        mask_list = self.net_mask.split('.')
        and_result_list = list(map(lambda x: str(int(x[0]) & int(x[1])), list(zip(ip_list, mask_list))))
        return '.'.join(and_result_list)

    @property
    def host_address(self):
        ip_list = self.ip_addr.split('.')
        mask_list = self.net_mask.split('.')
        rever_mask = list(map(lambda x: abs(255 - int(x)), mask_list))
        and_result_list = list(map(lambda x: str(int(x[0]) & int(x[1])), list(zip(ip_list, rever_mask))))
        return '.'.join(and_result_list)


if __name__ == '__main__':
    ip01 = IpAddrConverter("211.95.165.24", "255.255.254.0")
    ip02 = IpAddrConverter("211.95.164.78", "255.255.254.0")
    print(ip01.net_address == ip02.net_address)


免責聲明!

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



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