user1830004
user1830004

Reputation: 61

Python: string to hexa

I would like to convert a string containing an hexadecimal value (ex: 12ab) to that hexadecimal value (ex: 0x12ab) in python.

How could I do?

Upvotes: 0

Views: 138

Answers (2)

kaspersky
kaspersky

Reputation: 4097

If you want the string, it would be trivial:

your_hexa_value = '12ab'
answer = '0x' your_hexa_value

But if you want the numeric value (which I think you want),

int(your_hexa_value, 16)

would suffice. Notice, that internally, all numbers are represented in binary, so their base doesn't matter:

>>> 10 + 0x10 + 010  # 10 + 16 + 8
>>> 34

Upvotes: 1

Jon Clements
Jon Clements

Reputation: 142146

Something like:

   i = int('12ab', 16)
   # 4779
   hex(i)
   # '0x12ab'

Upvotes: 2

Related Questions