Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is -1 (or any negative value) represented in Python? [closed]

Tags:

python

I learned that in Python, integer precision is only limited to the constraints of your hardware. If you were to represent signed ints with 2's complement, the sign extension would go on forever. Does Python use a sign bit to represent them instead? Or something else?


1 Answers

CPython (the most common implementation) stores integral numbers as a PyLong type which contains an arbitrary amount of "pieces" which are unsigned numbers. The count of how many pieces there are is stored in the generic field ob_size which exists in every PyVarObject. This field is described as:

For statically allocated type objects, this should be initialized to zero. For dynamically allocated type objects, this field has a special internal meaning.

And indeed for PyLong, its meaning is quite special: it is the count of pieces in the number, but when the number is negative, ob_size is negative.

You can see it in action in _PyLong_Negate(), here: https://github.com/python/cpython/blob/master/Objects/longobject.c#L73 or perhaps even more clearly in PyLong_FromDouble(), here: https://github.com/python/cpython/blob/master/Objects/longobject.c#L328 - note that Py_SIZE() is just an accessor for the ob_size field.

like image 67
John Zwinck Avatar answered Dec 15 '25 17:12

John Zwinck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!