简体   繁体   中英

Convert int to a hex string in python

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. Eg 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM