Convert integer to hex-string with specific format

前端 未结 3 1681
长发绾君心
长发绾君心 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 04:02

    In Python 3.2 or above, you can use the to_bytes() method of the interger.

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

提交回复
热议问题