https://www.cnblogs.com/liao-lin/p/9882488.html)
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]之间的整数为对应的ASCLL字符串
<<<chr(65)
'A'
<<<chr(67)
'C'
<<<chr(90)
'Z'
<<<chr(97)
'a'
写一个ASCII和十六进制转换器
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位数字+字母的验证码
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))
程序猿(二进制)的浪漫
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())