Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex string variable to hex value conversion in python

Tags:

python

string

hex

I have a variable call hex_string. The value could be '01234567'. Now I would like to get a hex value from this variable which is 0x01234567 instead of string type. The value of this variable may change. So I need a generic conversion method.

like image 888
drdot Avatar asked Jun 20 '13 06:06

drdot


People also ask

Can you convert string to hex in Python?

Use hex() to convert a string to hex Use int(x, base) with 16 as base to convert the string x to an integer. Call hex(number) with the integer as number to convert it to hexadecimal.

How do you print a hex value of a string in Python?

hex() function 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 declare a hex value in Python?

When denoting hexadecimal numbers in Python, prefix the numbers with '0x'. Also, use the hex() function to convert values to hexadecimal format for display purposes.

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.


1 Answers

I think you might be mixing up numbers and their representations. 0x01234567 and 19088743 are the exact same thing. "0x01234567" and "19088743" are not (note the quotes).

To go from a string of hexadecimal characters, to an integer, use int(value, 16).

To go from an integer, to a string that represents that number in hex, use hex(value).

>>> a = 0x01234567
>>> b = 19088743
>>> a == b
True
>>> hex(b)
'0x1234567'
>>> int('01234567', 16)
19088743
>>>
like image 129
Jonathon Reinhart Avatar answered Sep 27 '22 23:09

Jonathon Reinhart