python 转换

一、字符串转16进制

str = "FF"
temp_value = int(str, 16)
print(hex(temp_value))

结果:0xFF

 

二、字符串转ASCII

ord('a')

结果:97

三、ASCII 转字符串

>>>print chr(0x30), chr(0x31), chr(0x61)   # 十六进制
0 1 a
>>> print chr(48), chr(49), chr(97)         # 十进制
0 1 a

 四、

s = b'\xaa'
print(type(s[0]))
print(s[0])

结果:

<class 'int'>
170 =0xaa

五、十六进制显示

字符串 hex()

print('%X'%item)

六、‘0xAA' 去掉0x

Python startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回 True,否则返回 False。如果参数 beg 和 end 指定值,则在指定范围内检查。

hex_list = ['0xAA', '0xED', '0xEF', '0xDE']
for x in hex_list:
    if x.startswith('0x'):
        x = x[2:]
        print x

七、文字转byes,在转16进制

def print_hex(bytes):
    l = [hex(int(i)) for i in bytes]
    print(l)
    print(" ".join(l))

def print_hex2(bytes):
    l = [int(i) for i in bytes]
    print(l)

d = "型号:"
s =d.encode('gbk')
print(s)
print_hex(s)
print_hex2(s)

b'\xd0\xcd\xba\xc5\xa3\xba'
['0xd0', '0xcd', '0xba', '0xc5', '0xa3', '0xba']
0xd0 0xcd 0xba 0xc5 0xa3 0xba
[208, 205, 186, 197, 163, 186]

 八、同上

send_list=[]
temp =[]

d = "型号:"
c="WH01-1"

for item in d:
    temp1 = item.encode('gbk')[0]
    temp2 = item.encode('gbk')[1]
    send_list.append(temp1)
    send_list.append(temp2)

for item in c:
    send_list.append(ord(item))

print(send_list)

for item in send_list:
    l = 'Ox%X'%item
    temp.append(l)

print(temp)

 九、 字节转字符串(16进制)

def hexShow(argv):  # 十六进制显示方法1
    try:
        result = ''
        hLen = len(argv)
        for i in range(hLen):
            hvol = argv[i]
            hhex = '%02x' % hvol
            result += hhex + ' '
        print('hexShow:', result)
    except:
        pass

aaa = b'\x80\x01\t\x00\x88'

hexShow(aaa)
# hexShow: 80 01 09 00 88 

 

 反向

strInput = "01 06 00 00 22 b8 91 18"
aaa=bytes.fromhex(strInput)
print(aaa)==>b'\x01\x06\x00\x00"\xb8\x91\x18'

 

 

 

posted @ 2020-04-29 16:41  做梦者造梦  阅读(406)  评论(0编辑  收藏  举报