0

I am trying to convert an int to hex in string. The current solutions do not work as intended.

The hex must be in \x format. E.g. 255 -> \xff; 65 -> \x41

Accepted Solution from a similar question

chr(1) # '\x01'; This is okay.
chr(65) # 'A'
chr(255) # 'ΓΏ'

The output is nothing like hex even if they equal to their corresponding hex values. The output has to be a \x formatted hex.

Using hex()

hex(1) # '0x1'
hex(65) # '0x41'
hex(255) # '0xff'

No luck here. x is followed by 0 so it is not useful. hex(1) does not have a 0 before the 1. I would like to have that. Better yet, a padding length of my choice. repr(chr(65)) as suggested in the comments does not work either.

hex() with replacement

chr(255).replace('0', "\\") # '\\xff'
hex(255).replace('0x', "\\x") # '\\xff'

Cannot use replace() either cause \ has to be escaped or the code does not even work. I really would like to avoid a solution that requires modifying a string since copying is involved.

int.to_bytes

int.to_bytes(1, 1, 'big') # b'\x01'
int.to_bytes(65, 1, 'big') # b'A'; Why is this suddenly 'A'? Why not b'\x41'
int.to_bytes(255, 1, 'big') # b'\xff'

A pythonic, performant solution to the problem is greatly appreciated.

Rashiq
  • 317
  • 1
  • 4
  • 13
  • 2
    The problem is that python automatically interprets `\xff` sequences back. So you have to write it escaped and then print the result (to get a single backslash) or you'll always have the interpreted version anyways – h4z3 Mar 25 '21 at 15:17
  • 1
    Eg take a look at the output for `print('\x41')`. `\x` in this context is an escape sequence, and one that will be omitted if it's not necessary. – Peter DeGlopper Mar 25 '21 at 15:18
  • However, you can encode string into bytes object. Byte values associated with ascii characters will get shown to you as those characters (for the sake of readability - sometimes bytes object is actually encoded string and this makes it easier to recognize what is what), while the rest will be still in its escape codes. But that also means the codes won't be exact - e.g. `"\xff".encode()` gives `b'\xc3\xbf'` – h4z3 Mar 25 '21 at 15:21

2 Answers2

0

what about using f-string, can use its format method to convert to hex and just append that to \x.

def int_to_hex(char_as_int: int) -> str:
    return rf"{char_as_int} -> \x{char_as_int:02x}"


for i in (65, 46, 78, 97, 145):
    print(int_to_hex(i))

OUTPUT

65 -> \x41
46 -> \x2e
78 -> \x4e
97 -> \x61
145 -> \x91
Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
0

Can you try this:

def convert_to_hex(num) -> str:
    return "\\" + str(hex(num))[1:]


print(convert_to_hex(1))

Sample Output:

1 -> \x1
2 -> \x2
254->\xfe
255->\xff
Brian Brix
  • 449
  • 4
  • 12