Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I format an integer to a two digit hex?

Tags:

python

Does anyone know how to get a chr to hex conversion where the output is always two digits?

for example, if my conversion yields 0x1, I need to convert that to 0x01, since I am concatenating a long hex string.

The code that I am using is:

hexStr += hex(ord(byteStr[i]))[2:] 
like image 448
AndroidDev Avatar asked Jul 26 '12 19:07

AndroidDev


People also ask

How can I convert a hex string to an integer value?

To convert a hexadecimal string to a numberUse the ToInt32(String, Int32) method to convert the number expressed in base-16 to an integer. The first argument of the ToInt32(String, Int32) method is the string to convert. The second argument describes what base the number is expressed in; hexadecimal is base 16.

What is hex string format?

The format for coding a hexadecimal string mask is: X'yy...yy' The value yy represents any pair of hexadecimal digits that constitute a byte (8 bits). Each bit must be 1 (test bit) or 0 (ignore bit). You can specify up to 256 pairs of hexadecimal digits.

How do you use hex 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 can use string formatting for this purpose:

>>> "0x{:02x}".format(13) '0x0d'  >>> "0x{:02x}".format(131) '0x83' 

Edit: Your code suggests that you are trying to convert a string to a hexstring representation. There is a much easier way to do this (Python2.x):

>>> "abcd".encode("hex") '61626364' 

An alternative (that also works in Python 3.x) is the function binascii.hexlify().

like image 111
Sven Marnach Avatar answered Sep 22 '22 17:09

Sven Marnach