Convert integer to hex-string with specific format

前端 未结 3 1688
长发绾君心
长发绾君心 2021-02-06 03:45

I am new to python and have following problem: I need to convert an integer to a hex string with 6 bytes.

e.g. 281473900746245 --> \"\\xFF\\xFF\\xBF\\xDE\\x16\\x05\"

3条回答
  •  别那么骄傲
    2021-02-06 03:53

    If you don't use Python 3.2 (I'm pretty sure you don't), consider the next approach:

    >>> 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'
    

提交回复
热议问题