Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - how to convert int to string represent a 32bit Hex number

I want to get a python solution for this problem:

e.g.

integer 1 -> string "0x00000001"
integer 64 -> string "0x00000040"
integer 3652458 -> string "0x0037BB6A"

The string size will not be change if number is in range(0, 2**32).

like image 856
william Avatar asked Aug 31 '11 07:08

william


People also ask

How will you convert an integer to hexadecimal 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.

How does Python convert int to string?

In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string.

Which method converts an integer to a hexadecimal string?

toHexString() method in Java converts Integer to hex string. Let's say the following are our integer values. int val1 = 5; int val2 = 7; int val3 = 13; Convert the above int values to hex string.

How do you represent a hexadecimal number in Python?

When denoting hexadecimal numbers in Python, prefix the numbers with '0x'.


1 Answers

Try this:

'0x%08X' % 3652458

or (with Python 2.6 and newer)

'0x{0:08X}'.format(3652458)

both return:

'0x0037BB6A'
like image 156
eumiro Avatar answered Sep 26 '22 03:09

eumiro