Convert integer to hex-string with specific format

前端 未结 3 1689
长发绾君心
长发绾君心 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'
    
    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2021-02-06 04:16

    There might be a better solution, but you can do this:

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

    Breakdown:

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

    Update:

    Per @multipleinstances and @Sven's comments, since you might be dealing with long values, you might have to tweak the output of hex a little bit:

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

    Sometimes, however, the output of hex might be an odd-length, which would break decode, so it'd probably be better to create a function to do this:

    def convert(int_value):
       encoded = format(int_value, 'x')
    
       length = len(encoded)
       encoded = encoded.zfill(length+length%2)
    
       return encoded.decode('hex')
    
    0 讨论(0)
提交回复
热议问题