简体   繁体   English

python,字符串到十六进制数组

[英]python, string to hex array

fast question, I want this (of course python3):快速的问题,我想要这个(当然是python3):

frame = "AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA"

to this:对此:

frame = [0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA, 0x5, 0x5, 0x5, 0xA, 0xA, 0xA]

We can try this:我们可以试试这个:

frame = "AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA"
[int(character, 16) for character in frame]
# [10, 10, 10, 5, 5, 5, 10, 10, 10, 5, ... ]

As @Reti43 notes in a comment , hexadecimal values like 0xA correspond to numbers like 10, so that's why the resulting list has integers.正如@Reti43 在评论中指出的那样,像0xA这样的十六进制值对应于像 10 这样的数字,这就是结果列表具有整数的原因。

If the OP desires hexadecimal, string representation can be used as below.如果 OP 需要十六进制,则可以如下使用字符串表示。 This string can then be passed to int to get the corresponding integer.然后可以将此字符串传递给int以获取对应的 integer。

frame = "AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA555AAA"
[f"0x{character}" for character in frame]
# ['0xA', '0xA', '0xA', '0x5', '0x5', '0x5', '0xA', '0xA', '0xA', '0x5', ...]

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

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