Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I do the equivelant of casting to int, in python

Tags:

python

c

I have a function that returns a value to me as a string. This is not the ascii representation of the value, this is the actual value, but the function returns it as a string type, while I need to treat it as an int. I'm not allowed to change the function I just have to extract my data out of it.

in C I would just cast it to an int pointer and derefrence it as such:

myInt = *((int*)some_str_ptr)

how could I do this in python?

Again, I don't want modify or convert the data in memory, I just want to treat it and display it as an int.

update: Ive found that ord() does what I want on 1 char, but is there a built in method to do the whole string?

like image 453
Siavash Avatar asked Mar 20 '23 18:03

Siavash


1 Answers

Check out the struct module:

>>> struct.unpack('i', 'AAAA')[0]  # 'i' means "long" integer
                                   # 'AAAA' was the string you wanted cast to int
1094795585
>>> hex(_)
0x41414141
like image 147
mhlester Avatar answered Apr 01 '23 01:04

mhlester