9

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"

The format of the hex-string is important. The length of the int value is variable.

The format '0xffffbf949309L' don't work for me. (I get this with hex(int-value))


My final solution (after some "playing") is:

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

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

    return hexed

Thank you for all the help!

3
  • 1
    Do you want the string of length 6 defined by the Python string literal "\xFF\xFF\xBF\xDE\x16\x05" or the string of length 24 given by "\\xFF\\xFF\\xBF\\xDE\\x16\\x05"? Commented Jul 29, 2011 at 14:48
  • The terms "hex string" and "format" are misleading, what you really want is to form an integer of arbitrary size to a byte string with big-endian order. Commented Jul 29, 2011 at 15:44
  • 1
    Please excuse my English - I just translated the terms from my first language - thank you for the translation. Commented Aug 2, 2011 at 10:06

3 Answers 3

13

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')
Sign up to request clarification or add additional context in comments.

5 Comments

On my system, hex(x)[2:] produces ffffbfde1605L, which causes a TypeError in decode. hex(x)[2:-1] might be better.
@multipleinterfaces: unconditionally stripping the last byte is a bad idea. hex(x)[2:].rstrip("L") should do the job, though.
@multiple Actually, this won't work for L values since the hex output can be an odd length (for some reason).
@Manny: Your solution does not work for any number that consists of an odd number of hex characters. For example, 2748 is 0xABC, and str.decode('hex') would require 0abc instead of abc.
To save yourself from the hassle with 0x prefix and L suffix, use format(number, 'x') instead of hex().
4

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'

2 Comments

Worth to mention that you will need to precompute the desired length (using math.log or int.bit_length) and probably want to specify byteorder='big'.
@Ferdinand: Thanks, expanded my answer.
1

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'

1 Comment

I tested this approach... it only works if the int-value isn't to short. e.g. with i=2 I get '\x02\x1d\x08\xff\xff\xbf\xde\x16\x05'...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.