python - 反转包含十六进制字符的字符串的字节顺序

标签 python python-3.x hex byte

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

string = "AA55CC3301AA55CC330F234567"

我正在使用

string.to_bytes(4, 'little')

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

6745230F33CC55AA0133CC55AA

但是我遇到了一个错误

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

这里有什么问题吗?

最佳答案

to_bytes 仅适用于整数,afaik。

你可以使用 bytearray :

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

使用 format 将它转换回字符串:

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

关于python - 反转包含十六进制字符的字符串的字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46109815/

相关文章:

python - 如何将矩阵顺时针旋转 90 度?

python - 如何阻止梯度提升机过度拟合?

python-3.x - 使用 Selenium 抓取(Python)时只有第一行

python - 在 numpy 中导入非方表

algorithm - 在不使用固定长度变量存储结果的情况下将十六进制数转换为十进制形式的最快算法

c - 获取十六进制数字的字符表示(创建 char* 以显示十六进制值)

python - 使用python确定相对复杂的数学表达式中的分子和分母

python - 命名元组的子类化集合

python - 比较 Pandas 中数据帧的标题

string - 在 masm 中解码十六进制(空字节问题)