13

I have a script that calls a function that takes a hexadecimal number for an argument. The argument needs to the 0x prefix. The data source is a database table and is stored as a string, so it is returned '0x77'. I am looking for a way to take the string from the database and use it as an argument in hex form with the 0x prefix.

This works:

addr = 0x77
value = class.function(addr)

The database entry has to be a string, as most of the other records do not have hexadecimal values in this column, but the values could be changed to make it easier, so instead of '0x77', it could be '119'.

1
  • class.function(119) and class.function(0x77) are completely equivalent calls. Commented Feb 10, 2014 at 4:59

3 Answers 3

14

Your class.function expects an integer which can be represented either by a decimal or a hexadecimal literal, so that these two calls are completely equivalent:

class.function(0x77)
class.function(119)  # 0x77 == 119

Even print(0x77) will show 119 (because decimal is the default representation).

So, we should rather be talking about converting a string representation to integer. The string can be a hexadecimal representation, like '0x77', then parse it with the base parameter:

 >>> int('0x77', 16)
 119

or a decimal one, then parse it as int('119').

Still, storing integer whenever you deal with integers is better.

EDIT: as @gnibbler suggested, you can parse as int(x, 0), which handles both formats.

Sign up to request clarification or add additional context in comments.

2 Comments

If you use 0 as the second parameter to int, it will convert both decimal and hexadecimal values correctly
@gnibbler just wow. Heck, that's right there in the docs, and it's the first time I hear about that!
8
>>> hex(119)
'0x77'
#or:
>>> hex(int("119"))
'0x77'

This should work for you.

You can also get the hex representation of characters:

>>> hex(ord("a"))
'0x61'

Comments

1

I think you're saying that you read a string from the database and you want to convert it to an integer, if the string has the 0x prefix you can convert it like so:

>>> print int("0x77", 16)
119

If it doesnt:

>>> print int("119")
119

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.