Python: get int value from char string

This is one of those stupid questions, and I donโ€™t know how to formulate it, so Iโ€™ll give an example. I got

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

where #AEAE in decimal value is 44718.

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

Thanks.

+4
source share
5 answers

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 
+3
source

You can convert a string of bytes of arbitrary length to 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 one of them for data with small ends and the other for data in large format. Or vice versa.

+2
source

I assume that you want to convert hex to an integer, not a char string.

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

or

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

In response to your comment, one of the ways I can come up with is to use bit shifts:

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

I am not sure if there is a better way.

+1
source

Well, the straightforward path:

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

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

You can flip v in advance to get the opposite endian-ness.

+1
source

It is easier to save the hex text as a string and use int() :

 int("AEAE", 16) 
0
source

Source: https://habr.com/ru/post/1479805/


All Articles