首页 > 解决方案 > 字符串到字节 Python

问题描述

我正在尝试将字符串转换为字节。该字符串包含一个整数,我必须将其转换为十六进制。例如: example : stringAddress = '32000' 我希望它变成 byte = b'\x7D\x00\x00

我的代码给了我 byte =b' \\x7d \\x00 \\x00

当我尝试“替换”'\\'字节更改时...在 b'}\x14\x00'

这是我的代码

from codecs import encode


numero = '32020'
numerohex = hex(int(numero))[2:]
print(numerohex)

 

if len(numerohex) == 4:
    newnumero = r'\x{}\x{}\x00'.format(numerohex[:2], numerohex[2:4])
elif len(numerohex) == 3:
    newnumero = r'\x0{}\x{}\x00'.format(numerohex[:1], numerohex[1:3])
elif len(numerohex) == 2:
    newnumero = r'\x00\x{}\x00'.format(numerohex)
elif len(numerohex) == 1:
    newnumero = r'\x00\x0{}\x00'.format(numerohex)

 

tmp = bytes(newnumero, encoding='raw_unicode_escape')

 

print(bytes(newnumero, encoding='raw_unicode_escape'))
print(encode(newnumero.encode().decode('unicode_escape'), "raw_unicode_escape"))

有人能帮我吗?

标签: pythonstringhexbyte

解决方案


推荐阅读