@@ -23,6 +23,28 @@ typedef struct _longobject PyLongObject; /* Revealed in longintrepr.h */
2323
2424``` c
2525// longintrepr.h
26+ /* Long integer representation.
27+ The absolute value of a number is equal to
28+ 一个数的绝对值等价于下面的表达式
29+ SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
30+
31+ Negative numbers are represented with ob_size < 0;
32+ 负数表示为 ob_size < 0
33+
34+ zero is represented by ob_size == 0.
35+ 整数0 用 ob_size == 0表示
36+
37+ In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
38+ digit) is never zero. Also, in all cases, for all valid i,
39+
40+ 0 <= ob_digit[i] <= MASK.
41+
42+ The allocation function takes care of allocating extra memory
43+ so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
44+
45+ CAUTION: Generic code manipulating subtypes of PyVarObject has to
46+ aware that ints abuse ob_size's sign bit.
47+ */
2648
2749struct _longobject {
2850 PyObject_VAR_HEAD
@@ -132,6 +154,8 @@ get_small_int(sdigit ival)
132154 } while(0)
133155```
134156
157+ 宏**CHECK_SMALL_INT**会检查传入的数是否在小整数范围内,如果是直接返回
158+
135159
136160### 小整数初始化
137161
@@ -188,3 +212,58 @@ _PyLong_Init(void)
188212 return 1;
189213}
190214```
215+
216+
217+ ## 整数的存储结构
218+
219+ ` 源文件: ` [ Objects/longobject.c] ( https://github.com/python/cpython/blob/v3.7.0/Objects/longobject.c#L1581 )
220+
221+ 在 ** long_to_decimal_string_internal** 中添加如下代码并重新编译安装
222+ ``` c
223+ // Objects/longobject.c
224+ static int
225+ long_to_decimal_string_internal (PyObject * aa,
226+ PyObject ** p_output,
227+ _ PyUnicodeWriter * writer,
228+ _ PyBytesWriter * bytes_writer,
229+ char ** bytes_str)
230+ {
231+ PyLongObject * scratch, * a;
232+ PyObject * str = NULL;
233+ Py_ssize_t size, strlen, size_a, i, j;
234+ digit * pout, * pin, rem, tenpow;
235+ int negative;
236+ int d;
237+ enum PyUnicode_Kind kind;
238+
239+ a = (PyLongObject *)aa;
240+
241+ // 添加打印代码
242+ printf("ob_size = %d\n", Py_SIZE(a));
243+ for (int index = 0; index < Py_SIZE(a); ++index) {
244+ printf("ob_digit[%d] = %d\n", index, a->ob_digit[index]);
245+ }
246+
247+ ...
248+ }
249+ ```
250+
251+ 编译安装后进入python解释器输入如下代码
252+
253+ ```python
254+ num = 9223372043297226753
255+ print(num)
256+
257+ # output
258+ >>> ob_size = 3
259+ >>> ob_digit[0] = 1
260+ >>> ob_digit[1] = 6
261+ >>> ob_digit[2] = 8
262+ >>> 9223372043297226753
263+ ```
264+
265+ 如下图所示
266+
267+ ![ longobject storage] ( longobject_storage.png )
268+
269+
0 commit comments