简体   繁体   English

如何将字节列表从十进制更改为十六进制?

[英]how can I change a byte list from decimal to hex?

basically, I have a list of bytes, and I want to convert that to ASCII text基本上,我有一个字节列表,我想将其转换为 ASCII 文本

so I converted that list into a single bytearray (I apologize if that's the wrong term), to then be able to convert it into ASCII text所以我将该列表转换为单个 bytearray(如果这是错误的术语,我深表歉意),然后能够将其转换为 ASCII 文本

but since that list has the values seen as decimal, I have issues to convert it to text, since i would need them to be in hex.但由于该列表的值被视为十进制,我无法将其转换为文本,因为我需要它们为十六进制。 (obs: the values are in hex, they are just not represented as it) (obs:这些值是十六进制的,它们只是没有表示成它)

ok, so this is the initial list:好的,这是初始列表:

text_bytes_list = [b'74', b'68', b'69', b'73', b'20', b'69', b'73', b'20', b'61', b'20', b'74', b'65', b'73', b'74']

and I did this to get it all in a single byte:我这样做是为了在一个字节中完成所有操作:

text_byte = b''.join(text_byte_list)
print(text_byte)

the output is: b'7468697320697320612074657374' output 是: b'7468697320697320612074657374'

so what I wanted was a way to turn this:所以我想要的是一种方法来改变这个:

text_bytes_list = [b'74', b'68', b'69', b'73', b'20', b'69', b'73', b'20', b'61', b'20', b'74', b'65', b'73', b'74']

into this:进入这个:

text_bytes_list = [b'0x74', b'0x68', b'0x69', b'0x73', b'0x20', b'0x69', b'0x73', b'0x20', b'0x61', b'0x20', b'0x74', b'0x65', b'0x73', b'0x74']

so when I joined the list, using the same process I would get:所以当我加入列表时,使用相同的过程我会得到:

text_byte = b''.join(text_byte_list)
print(text_byte)

output: b'\x74\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74' output: b'\x74\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74'

with that value I can convert it into text (my objective here), doing this:有了这个值,我可以将它转换成文本(我的目标在这里),这样做:

text_byte = b'\x74\x68\x69\x73\x20\x69\x73\x20\x61\x20\x74\x65\x73\x74'
print(text_byte.decode("ascii"))

the output should be: this is a test output 应该是:这是一个测试

sorry, the post got a little big, but I appreciate any help I can get, pls help:)抱歉,帖子有点大,但我很感激我能得到的任何帮助,请帮忙:)

Just convert them to integers, and then into a "bytes" string.只需将它们转换为整数,然后转换为“字节”字符串即可。

>>> text_bytes_list = [b'74', b'68', b'69', b'73', b'20', b'69', b'73', b'20', b'61', b'20', b'74', b'65', b'73', b'74']
>>> tbl = [int(t,16) for t in text_bytes_list]
>>> tbl
[116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116]
>>> bytes(tbl)
b'this is a test'
>>>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM