Python: converting a string representing an hexadecimal integer representation into an int variable

Submitted by fabio on Wed, 2010-08-11 18:27.

Recently I had the need to convert a string containing the hexadecimal representation of an integer into an integer variable.

Eg, with something like FFAA, create an integer variable with the value of 65450.

In some programming languages there is an unhex() function but not in python.

In order to do so you'll need to use int(). If called with two arguments, int() expects the first to be a string representing a number in some base and the second to be the base.

So, if you run a = int("FFAA", 16), a will be an integer having value of 65450.

Some more examples:

print int(hex(65450), 16)
print int("0xffaa", 16)
print int("ffaa", 16)

The above will produce:

65450
65450
65450

Questions, suggestions or comments? Please leave a comment below. Thanks!

Posted in:

Post new comment

The content of this field is kept private and will not be shown publicly.
If you have a personal or company website insert its address in the form http://www.example.com/ .
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <pre> <del> <img> <h2> <h3> <h4> <b> <video> <sub> <sup>
  • Lines and paragraphs break automatically.
  • Images can be added to this post.
  • You may use [inline:xx] tags to display uploaded files or images inline.
  • You may insert videos with [video:URL]
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.

More information about formatting options