将整数转换为具有特定格式的十六进制字符串

2024-06-02 12:31:15 发布

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

我是python新手,遇到了以下问题:我需要将一个整数转换为一个6字节的十六进制字符串。

例如。 281473900746245-->;“\xFF\xFF\xBF\xDE\x16\x05”

十六进制字符串的格式很重要。int值的长度是可变的。

格式“0xffffbf949309L”对我不起作用。(我用十六进制(int值)得到这个)


我的最终解决方案(在“播放”一段时间后)是:

def _tohex(self, int_value):
    data_ = format(int_value, 'x')

    result = data_.rjust(12, '0')
    hexed = unhexlify(result)

    return hexed

谢谢你的帮助!


Tags: 字符串gtdata字节value格式整数result
3条回答

在Python 3.2或更高版本中,可以使用integer的^{}方法。

>>> i = 281473900746245       
>>> i.to_bytes((i.bit_length() + 7) // 8, "big")
b'\xff\xff\xbf\xde\x16\x05'

如果您不使用Python3.2(我很确定您没有),请考虑下一种方法:

>>> i = 281473900746245
>>> hex_repr = []
>>> while i:
...     hex_repr.append(struct.pack('B', i & 255))
...     i >>= 8
...
>>> ''.join(reversed(hex_repr))
'\xff\xff\xbf\xde\x16\x05'

可能有更好的解决方案,但您可以这样做:

x = 281473900746245
decoded_x = hex(x)[2:].decode('hex') # value: '\xff\xff\xbf\xde\x16\x05'

故障:

hex(x)                     # value: '0xffffbfde1605'
hex(x)[2:]                 # value: 'ffffbfde1605'
hex(x)[2:].decode('hex')   # value: '\xff\xff\xbf\xde\x16\x05'

更新:

根据@multipleinstances和@Sven的注释,由于您可能要处理长值,因此可能需要稍微调整hex的输出:

format(x, 'x')     # value: 'ffffbfde1605'

但是,有时十六进制的输出可能是奇数长度,这会中断解码,因此最好创建一个函数来执行此操作:

def convert(int_value):
   encoded = format(int_value, 'x')

   length = len(encoded)
   encoded = encoded.zfill(length+length%2)

   return encoded.decode('hex')

相关问题 更多 >