Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an int to a hex string?

I want to take an integer (that will be <= 255), to a hex string representation

e.g.: I want to pass in 65 and get out '\x41', or 255 and get '\xff'.

I've tried doing this with the struct.pack('c',65), but that chokes on anything above 9 since it wants to take in a single character string.

like image 248
pynoob Avatar asked Feb 16 '10 00:02

pynoob


People also ask

How do you convert int to hex in python?

hex() function is one of the built-in functions in Python3, which is used to convert an integer number into it's corresponding hexadecimal form. Syntax : hex(x) Parameters : x - an integer number (int object) Returns : Returns hexadecimal string.

How do you hex a string in Python?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.


1 Answers

You are looking for the chr function.

You seem to be mixing decimal representations of integers and hex representations of integers, so it's not entirely clear what you need. Based on the description you gave, I think one of these snippets shows what you want.

>>> chr(0x65) == '\x65' True   >>> hex(65) '0x41' >>> chr(65) == '\x41' True 

Note that this is quite different from a string containing an integer as hex. If that is what you want, use the hex builtin.

like image 74
Mike Graham Avatar answered Sep 28 '22 03:09

Mike Graham