-2

I have a variable with value like a ="\x01" from my database, how can I convert it into an integer. I have searched the internet but had no success in finding anything.

Anyone have an idea?

In PHP, there is a build-in module to convert it. Is there any similar module for that function in Python?

user458766
  • 35
  • 6
  • How about `int(a)`...!? It's a bit unclear what exactly the contents of `a` are here and how that should convert to an int. – deceze Jan 16 '16 at 14:54
  • @deceze That doesn't work. That byte literal is not a valid integer. – chepner Jan 16 '16 at 14:55
  • 1
    @chepner That would be the same problem with PHP's `(int)`, so it's rather ambiguous. I also don't trust this to be an actual literal and not some pseudo-notation. – deceze Jan 16 '16 at 14:57
  • Possible duplicate of [ASCII value of a character in Python](http://stackoverflow.com/questions/227459/ascii-value-of-a-character-in-python) – GingerPlusPlus Jan 16 '16 at 15:11

2 Answers2

4

Simple answer is to use ord().

>>> a = '\x01'
>>> ord(a)
1

But if performance is what you are looking for then refer @chepner's answer.

Community
  • 1
  • 1
JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
0

You can use the struct module for fixed-length values.

>>> a = '\x01'
>>> import struct
>>> struct.unpack("B", a)
(1,)

unpack always returns a tuple, since you can extract multiple values from a single string.

GingerPlusPlus
  • 5,336
  • 1
  • 29
  • 52
chepner
  • 497,756
  • 71
  • 530
  • 681