0

I want to convert a decimal integer into a \xLO\xHI hex string while keeping the "\x" prefix and without translating printable ASCII to their equivalent ASCII.

What I want to achieve:

>>> dec_to_hex(512)
"\x00\x02"

The following solutions I found while searching for an answer aren't good enough and I'll explain why:

This one didn't put the "\x" prefix and don't translated it to bytes

>>> hex(512)
'0x200'

This examples is really close but receives hexadecimal (I need decimal) and translated chars to ascii:

>>> from binascii import unhexlify
>>> unhexlify('65004100430005FF70000000')
'e\x00A\x00C\x00\x05\xffp\x00\x00\x00'

This one translates ASCIIinto chars:

>>> import struct
>>> struct.pack('<h', 512)
'\x00\x02'
>>> struct.pack('<h', 97)
'a\x00'
api pota
  • 109
  • 12
  • Have you tried the answers from [this](https://stackoverflow.com/questions/11683294/convert-integer-to-hex-in-python) thread? Regarding little endian you can use 'I' which will be big endian. – Spezi94 Jan 23 '18 at 14:32
  • `struct` translates ascii into characters (97 to 'a', 103 to 'g' etc). – api pota Jan 23 '18 at 14:35
  • The other answer is close, `print re.sub(r'([0-9A-F]{2})',r'\\x\1','%04X' % 512)` but isn't a little endian – api pota Jan 23 '18 at 14:35
  • Have you tried the repr() function? See [this](https://stackoverflow.com/questions/37990060/python-struct-pack-behavior) thread how to use it. Example code: `repr(struct.pack(' – Spezi94 Jan 23 '18 at 14:52
  • it translates 97 to "a" as well – api pota Jan 24 '18 at 14:37

0 Answers0