将十六进制数转换为字符字符串颠倒



我有这个变量

x = 0x61626364

我想要字符串"dcba",以字符转换十六进制数,然后反转字符串。

我怎样才能在 python 中做到这一点?

使用int.to_bytes()方法将整数解释为小端序的字节:

>>> x = 0x61626364
>>> x.to_bytes(4, 'little')
b'dcba'

您确实需要知道此的输出长度。

你可以试试这个:

x = 0x61626364
print(x.to_bytes(4, 'little').decode('utf-8'))

解释:

使用to_bytes()

我们将获取字节码并获取字符串dcba使用解码函数。

输出:

dcba
import math
a = [chr(0xFF&(x>>(8*i))) for i in range(math.ceil(math.log(x, 2)/8))]
b = ""
for i in range(len(a)): b += a[i]
print(b)

享受!

def convert(h):
result = ''
while h>0:
result+=chr(h%256)
h//=256
return result

>>> convert(0x61626364)
'dcba'
>>> convert(0x21646c726f57206f6c6c6548)
'Hello World!'

最新更新