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)
Python内置进制转换函数(实现16进制和ASCII转换)的更多相关文章
- Python内置的字符串处理函数整理
Python内置的字符串处理函数整理 作者: 字体:[增加 减小] 类型:转载 时间:2013-01-29我要评论 Python内置的字符串处理函数整理,收集常用的Python 内置的各种字符串处理 ...
- python内置常用高阶函数(列出了5个常用的)
原文使用的是python2,现修改为python3,全部都实际输出过,可以运行. 引用自:http://www.cnblogs.com/duyaya/p/8562898.html https://bl ...
- Python内置的字符串处理函数
生成字符串变量 str='python String function' 字符串长度获取:len(str) 例:print '%s length=%d' % (str,len(str)) 连接字符 ...
- Python 内置的一些高效率函数用法
1. filter(function,sequence) 将sequence中的每个元素,依次传进function函数(可以自定义,返回的结果是True或者False)筛选,返回符合条件的元素,重组 ...
- Python内置函数系列
Python内置(built-in)函数随着python解释器的运行而创建.在Python的程序中,你可以随时调用这些函数,不需要定义. 作用域相关(2) locals() :以字典类型返回当前位置 ...
- Python内置高阶函数map()
map()函数map()是 Python 内置的高阶函数,它接收一个函数 f 和一个 list,并通过把函数 f 依次作用在 list 的每个元素上,得到一个新的 list 并返回. 例如,对于lis ...
- Python内置函数进制转换的用法
使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...
- Python 内置函数进制转换的用法(十进制转二进制、八进制、十六进制)
使用Python内置函数:bin().oct().int().hex()可实现进制转换. 先看Python官方文档中对这几个内置函数的描述: bin(x)Convert an integer numb ...
- python 练习题:请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串
# -*- coding: utf-8 -*- # 请利用Python内置的hex()函数把一个整数转换成十六进制表示的字符串 n1 = 255 n2 = 1000 print(hex(n1)) pr ...
随机推荐
- 冒泡排序(JAVA实现)
基本思想:在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒. 即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将 ...
- Java学习--抽象类和接口
https://www.cnblogs.com/dolphin0520/p/3811437.html 抽象类 先了解一下[抽象方法]—一种特殊的方法,只有声明,没有具体的实现 abstract vo ...
- Linux —— 命令
Linux —— 命令 各种查看 查看文件绝对路径 pwd 查看某服务占用端口 netstat -ano |grep mysql Linux 下的复制粘贴 0.在KDE/Gnome下: 复制命令:Ct ...
- 806. Number of Lines To Write String
806. Number of Lines To Write String 整体思路: 先得到一个res = {a : 80 , b : 10, c : 20.....的key-value对象}(目的是 ...
- 浅析MySQL InnoDB的隔离级别
MySQL InnoDB存储引擎中事务的隔离级别有哪些?对应隔离级别的实现机制是什么? 本文就将对上面这两个问题进行解答,分析事务的隔离级别以及相关锁机制. 隔离性简介 隔离性主要是指数据库系统提供一 ...
- OO第二单元总结(多线程的电梯调度)
经过第一单元作业的训练,在做第二单元的作业的时候,要更加的有条理.但是第二次作业多线程的运行,带来了更多的运行的不确定性.呈现出来就是程序会出现由于线程安全问题带来的不可复现的bug.本单元的作业也让 ...
- UML作业第一次:UML用例图绘制
UML第一次作业 一. 用例图:用例图(usecase diagram)是UML用于描述软件功能的图形.用例图包括用例.参与者及其关系,用例图也可以包括注释和约束.程序员要画时序图啥的用其他的比较麻烦 ...
- 用matlab画两个曲面的图
求助!!用matlab画两个曲面的图 这是我写的程序,但是运行不出来,麻烦帮我修改一下,谢谢!!clearallcloseall[x,y]=meshgrid(0:.1:60);z1=(25*y-25* ...
- Qt QSpinBox 和 QDoubleSpinBox
展示一个效果: QDoubleSpinBox跟QSpinBox类似,只是多了一个decimal.
- nginx+fastCGI
首先贴些遇到的问题,之后再整理 1.yum -y install pcre zlib OpenSSL openssl-devel pcre-devel 2. nginx: [emerg] " ...