4

I have an array of 4 bytes that I need to print it's value as an Integer. This is very easy in C, as I can cast and print with something like this:

 printf("Integer Value = %i", (int) pointer_to_4_bytes_array);

Thanks.

OSM10
  • 61
  • 6
  • 1
    Your C code doesn't do what you say it does. Even if you change it to cast to an `int *` and dereference the pointer, the result is going to be platform-specific. – user2357112 Apr 19 '14 at 04:09
  • possible duplicate of [convert a string of bytes into an int (python)](http://stackoverflow.com/questions/444591/convert-a-string-of-bytes-into-an-int-python) – Robᵩ Apr 19 '14 at 04:12

3 Answers3

5

In Python2 (works on 3 too), you can use the struct module.

>>> import struct
>>> struct.unpack(">L","1234")[0]
825373492

In Python3.2+, int.from_bytes does what you want. See @ryrich's answer

>>> int.from_bytes(b"1234",'big')
825373492
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • `struct` could be used on both Python 2 and 3 if you use `bytes` literal: `b'1234'`. – jfs Apr 19 '14 at 04:20
2

I believe you're looking for int.from_bytes

Note : for Python 3.2

ryrich
  • 2,164
  • 16
  • 24
1

If your on Python 3.2+ there is a function:

int.from_bytes()

For python 2 you can use struct.

clutton
  • 620
  • 1
  • 8
  • 18