在进行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)

Python内置进制转换函数(实现16进制和ASCII转换)的更多相关文章

  1. Python内置的字符串处理函数整理

    Python内置的字符串处理函数整理 作者: 字体:[增加 减小] 类型:转载 时间:2013-01-29我要评论 Python内置的字符串处理函数整理,收集常用的Python 内置的各种字符串处理 ...

  2. python内置常用高阶函数(列出了5个常用的)

    原文使用的是python2,现修改为python3,全部都实际输出过,可以运行. 引用自:http://www.cnblogs.com/duyaya/p/8562898.html https://bl ...

  3. Python内置的字符串处理函数

    生成字符串变量 str='python String function'   字符串长度获取:len(str) 例:print '%s length=%d' % (str,len(str)) 连接字符 ...

  4. Python 内置的一些高效率函数用法

    1.  filter(function,sequence) 将sequence中的每个元素,依次传进function函数(可以自定义,返回的结果是True或者False)筛选,返回符合条件的元素,重组 ...

  5. Python内置函数系列

    Python内置(built-in)函数随着python解释器的运行而创建.在Python的程序中,你可以随时调用这些函数,不需要定义. 作用域相关(2) locals()  :以字典类型返回当前位置 ...

  6. Python内置高阶函数map()

    map()函数map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 例如,对于lis ...

  7. Python内置函数进制转换的用法

    使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...

  8. Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制)

    使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...

  9. python 练习题:请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串

    # -*- coding: utf-8 -*- # 请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串 n1 = 255 n2 = 1000 print(hex(n1)) pr ...

随机推荐

  1. 2019-04-25t16:19:49 转成正常的年月日

    1.首先得到的值时2019-04-25t16:19:49 2.想转成2019-04-25 3. var d = new Date(2019-04-25t16:19:49); var yy = d.ge ...

  2. 转载:Android RecyclerView 使用完全解析 体验艺术般的控件

    转自:https://blog.csdn.net/lmj623565791/article/details/45059587

  3. action,func简洁用法

     new Action(() => { }).Invoke();new Action(() => { })();    new Func<int, int>(s => { ...

  4. python练习题-day25

    class Person: __key=123 def __init__(self,username,password): self.username=username self.__password ...

  5. ADB——查看手机设备信息

    查看设备信息 查看手机型号 adb shell getprop ro.product.model 查看电池状况 adb shell dumpsys battery ''' Current Batter ...

  6. Scala中foldLeft的总结

    源码分析 def seq: TraversableOnce[A] 上面两段代码是scala.collection.TraversableOnce特质的foldLeft方法源代码,实现了Traversa ...

  7. Java 基础 IO流之序列化

    一,前言 在前面的IO中,我们都是讲数据以字符串的形式保存.能不能将一个数组保存到文件呢,当取出数据时也是一个数组,如果能够实现那就完美了.我们都知道比较通用的有JSON格式的序列化,那java中也有 ...

  8. 谷歌将一些弱小的库从安卓代码移除Google Removes Vulnerable Library from Android

    Google this week released the November 2018 set of security patches for its Android platform, which ...

  9. net Core TOptions和热更新

    TOptions接口 net Core 项目有个appsettings.json文件,程序默认也是读取的这个文件,appsettings.json是一个配置文件 我们可以把appsettings.js ...

  10. arcgis for JavaScript API 4.5与4.3的区别

    arcgis 4.5与4.3区别: 鉴于本人使用4.3时间比较久,而arcgis for JavaScript API于9月28日推出了4.5版本,但是直接更换4.5的init.js会出现意想不到的错 ...