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

时间:2018-05-23 11:11:56

标签: python string python-3.x python-2.7 hex

我有这个变量

x = 0x61626364

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

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

4 个答案:

答案 0 :(得分:1)

使用int.to_bytes() method

以小端顺序将整数解释为字节
>>> x = 0x61626364
>>> x.to_bytes(4, 'little')
b'dcba'

您需要知道此输出长度。

答案 1 :(得分:0)

你可以试试这个:

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

说明:

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

输出:

dcba

答案 2 :(得分:0)

享受!

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


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

答案 3 :(得分:0)

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)