Python中将字符串从big-endian转换为little-endian或反之亦然

2024-05-14 15:15:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个十六进制字符的长字符串。
例如:

string = "AA55CC3301AA55CC330F234567"

我正在使用

string.to_bytes(4, 'little')

我希望最后的字符串如下:

6745230F33CC55AA0133CC55AA

但我犯了个错误

AttributeError: 'str' object has no attribute 'to_bytes'

这里怎么了?


Tags: tono字符串stringbytesobject错误attribute
3条回答

也许你可以反转字符串

string = "AA55CC3301AA55CC330F234567"[::-1]

注意,您的问题与this question from 2009非常相似。虽然旧线程要求单向转换,而您要求“反之亦然”转换,但实际上是相同的事情,无论您从哪一个端开始。让我展示一下

0x12345678 -> 0x78563412 -> 0x12345678

使用为软件黑客创建的工具pwntools,转换非常容易。特别是,为了避免包装拆箱的混乱,pwntools embeds p32() function for exact this purpose

import pwntools

x2 = p32(x1)

^{}仅适用于整数afaik。

您可以使用^{}

>>> ba = bytearray.fromhex("AA55CC3301AA55CC330F234567")
>>> ba.reverse()

要使用^{}将其转换回字符串,请执行以下操作:

>>> s = ''.join(format(x, '02x') for x in ba)
>>> print(s.upper())
6745230F33CC55AA0133CC55AA

相关问题 更多 >

    热门问题