1

How can I treat a string which is a hexadecimal number as a hexadecimal number? For example, I am loading in a file of hexadecimal numbers but Python is loading the file in as a string. Is it possible to get Python to treat the hexadecimal numbers in the file as hexadecimal numbers? I'm using Python 2.7

Thanks!

user3452305
  • 27
  • 1
  • 4

1 Answers1

1

Use int, specifying base-16:

>>> int('FFABCD', 16)
16755661

Edit in reply to comment: OK, misunderstood.

>>> hex(int('0061', 16))
'0x61'

Works I suppose, but I won't be surprised if someone responds with a simpler way.

grayshirt
  • 615
  • 4
  • 13
  • 1
    Thanks for your reply! But the problem is, I have a number that is already a hexadecimal number, for example 0061, but currently it's being treated like a string but I would like Python to realise it's a hexadecimal number already. When I use the int() function it changes to 97, but I need the number to stay as it is because it's already hexadecimal, Python just thinks it's a string. – user3452305 Mar 23 '14 at 20:27
  • @user3452305: Use `int` if you need a number. The string representation is in base 10, but it isn't a "decimal number" or a "hexadecimal number". `hex` converts a number to a string that's a hexadecimal literal. – Eryk Sun Mar 23 '14 at 21:47
  • @user3452305: I wonder if maybe your file is a byte string that has been hex encoded, e.g. `codecs.encode(b'\x00\x61', 'hex_codec') == b'0061'`. In that case you'd open the file as `f = codecs.open(filename, encoding='hex_codec')`. – Eryk Sun Mar 23 '14 at 21:47