4

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Siavash
  • 7,583
  • 13
  • 49
  • 69

1 Answers1

7

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
mhlester
  • 22,781
  • 10
  • 52
  • 75
  • I tried this on a sample string of "aaaa", which should be 0x41414141 in memory (1094795585 in dec), but what I get is: >>> struct.unpack('l','aaaa') (1633771873,) – Siavash Jan 28 '14 at 23:38
  • 5
    @Siavash 'a' is 0x61 (97) in ASCII. You get 1633771873 = 0x61616161 which is correct. 'A' is 0x41, so if you tried the string "AAAA", you would get 0x41414141. – Sinkingpoint Jan 28 '14 at 23:44