Domanda

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.

È stato utile?

Soluzione

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

Altri suggerimenti

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.

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.

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.

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

int("AEAE", 16)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top