4

This is one of those silly questions and I don't really know how to formulate it, so I'll give an example. I got

v = chr(0xae) + chr(0xae)

where #AEAE is, in decimal, the value of 44718.

My question is how I get the integer value of v? I know about ord() but I can use it only for a char, and not for a string.

Thank you.

ov1d1u
  • 958
  • 1
  • 17
  • 38

5 Answers5

3

I managed to do this using the struct module:

import struct
int_no = struct.unpack('>H', v)[0]
print int_no

which outputs the desired results:

44718
ov1d1u
  • 958
  • 1
  • 17
  • 38
2

You can convert an arbitrary-length string of bytes to an int or long using one of these expressions.

i = reduce(lambda x, y: (x<<8)+ord(y), v, 0)
i = reduce(lambda x, y: (x<<8)+ord(y), reversed(v), 0)

Use the one of them for little-endian data and the other for big-endian data. Or vice-versa.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
1

I'm assuming you want to convert a hexadecimal to an integer rather than a char string.

>>> int("AEAE",16)
44718 

or

>>> int("0xAEAE",16)
44718

In reply to your comment, one way I can think of would be to use bitshifts:

>>> (ord('\xae') << 8) | (ord('\xae'))
44718

I'm not sure if there is a better way though.

GWW
  • 43,129
  • 11
  • 115
  • 108
  • The issue is that I get this data from a remote server, which is represented as `'\xae\xae'`, so this is what I need to convert to `int()` – ov1d1u May 08 '13 at 18:43
1

Well, the straightforward way would be to go:

def convert(v):
    x = 0
    for c in v:
        x *= 256
        x += ord(c)
    return x

If you want to have the leftmost character to have the largest value.

You can reverse v beforehand to get the opposite endian-ness.

Theo Belaire
  • 2,980
  • 2
  • 22
  • 33
0

It's easier to keep the hex as a string and use int():

int("AEAE", 16)
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180