Question

We can define variables as integer values, e.g.

x = 3
y = -2

and then operate on bits with binary operators &, |, ^ and ~. The question is if we always get the same result on every architecture, or is the behavior architecture specific? Can we always assume a two's complement representation of integers?

Was it helpful?

Solution 2

From the python 2 documentation (emphasis mine):

Plain integers: These represent numbers in the range -2147483648 through 2147483647. (The range may be larger on machines with a larger natural word size, but not smaller.) When the result of an operation would fall outside this range, the result is normally returned as a long integer (in some cases, the exception OverflowError is raised instead). For the purpose of shift and mask operations, integers are assumed to have a binary, 2’s complement notation using 32 or more bits, and hiding no bits from the user (i.e., all 4294967296 different bit patterns correspond to different values).

So yes: the integers are architecture specific for Python 2.

From the Python 3 documentation:

Plain integers: These represent numbers in an unlimited range, subject to available (virtual) memory only. For the purpose of shift and mask operations, a binary representation is assumed, and negative numbers are represented in a variant of 2’s complement which gives the illusion of an infinite string of sign bits extending to the left.

So no: the integers are not architecture specific for Python 3.

OTHER TIPS

Python 2.x supports two integer types: int and long. int is based on the underlying C long type and long is an arbitrary precision type. Very early version of Python (pre-2.2), treated the types as two separate types but they were mostly combined in Python 2.2. Python 3.x only uses the arbitrary precision type.

Bit operations behave as if applied to arbitrary-precision 2's complement numbers. If required, an int will be automatically promoted to a long in Python 2.x.

The behavior is consistent across platforms.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top