将十进制int转换为小尾数字符串('\x#######…')

2024-10-04 11:31:10 发布

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

我想把一个整数值转换成一个十六进制的字符串,用小尾数表示。例如,5707435436569584000将变成'\x4a\xe2\x34\x4f\x4a\xe2\x34\x4f'

我的googlefu为我找到的只是hex(..),这给了我'0x4f34e24a4f34e180',这不是我想要的。

我可能可以手动拆分字符串并构建我想要的字符串,但我希望somone可以为我提供更好的选择。


Tags: 字符串手动数值xe2hex尾数x34x4a
2条回答

我知道这是一条老线索,但它仍然有用。这是我用Python的两分钱:

hex_string = hex(5707435436569584202) # '0x4f34e24a4f34e180' as you said
bytearray.fromhex(hex_string[2:]).reverse()

所以,关键是将其转换为bytearray并将其反转。 一行:

bytearray.fromhex(hex(5707435436569584202)[2:])[::-1] # bytearray(b'J\xe24OJ\xe24O')

注:您可以将“bytearray”数据视为“字节”,甚至可以将它们与b'raw bytes'混合使用

更新: 作为coments中的Will点,您还可以管理负整数:

To make this work with negative integers you need to mask your input with your preferred int type output length. For example, -16 as a little endian uint32_t would be bytearray.fromhex(hex(-16 & (2**32-1))[2:])[::-1], which evaluates to bytearray(b'\xf0\xff\xff\xff')

您需要使用^{} module

>>> import struct
>>> struct.pack('<Q', 5707435436569584000)
'\x80\xe14OJ\xe24O'
>>> struct.pack('<Q', 5707435436569584202)
'J\xe24OJ\xe24O'

这里<表示小结束符,并且Q表示我们要打包一个无符号的长(8字节)。

请注意,Python将对可打印ASCII范围内的任何字节使用ASCII字符来表示生成的bytestring,因此上述结果的14OJ24OJ部分:

>>> struct.pack('<Q', 5707435436569584202).encode('hex')
'4ae2344f4ae2344f'
>>> '\x4a\xe2\x34\x4f\x4a\xe2\x34\x4f'
'J\xe24OJ\xe24O'

相关问题 更多 >