How do languages such as Python overcome C's Integral data limits?

后端 未结 5 679
天命终不由人
天命终不由人 2021-01-15 16:06

While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:

In C, using \'unsigned long long\' data type, the

5条回答
  •  天命终不由人
    2021-01-15 16:29

    Looking at the Python source code, it seems the long type (at least in pre-Python 3 code) is defined in longintrepr.h like this -

    /* Long integer representation.
       The absolute value of a number is equal to
        SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
       Negative numbers are represented with ob_size < 0;
       zero is represented by ob_size == 0.
       In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
       digit) is never zero.  Also, in all cases, for all valid i,
        0 <= ob_digit[i] <= MASK.
       The allocation function takes care of allocating extra memory
       so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
    
       CAUTION:  Generic code manipulating subtypes of PyVarObject has to
       aware that longs abuse  ob_size's sign bit.
    */
    
    struct _longobject {
        PyObject_VAR_HEAD
        digit ob_digit[1];
    };
    

    The actual usable interface of the long type is then defined in longobject.h by creating a new type PyLongObject like this -

    typedef struct _longobject PyLongObject;
    

    And so on.

    There is more stuff happening inside longobject.c, you can take a look at those for more details.

提交回复
热议问题