2 /* Long (arbitrary precision) integer object implementation */
4 /* XXX The functional organization of this file is terrible */
7 #include "longintrepr.h"
11 #define ABS(x) ((x) < 0 ? -(x) : (x))
14 static PyLongObject
*long_normalize(PyLongObject
*);
15 static PyLongObject
*mul1(PyLongObject
*, wdigit
);
16 static PyLongObject
*muladd1(PyLongObject
*, wdigit
, wdigit
);
17 static PyLongObject
*divrem1(PyLongObject
*, digit
, digit
*);
18 static PyObject
*long_format(PyObject
*aa
, int base
, int addL
);
20 static int ticker
; /* XXX Could be shared with ceval? */
22 #define SIGCHECK(PyTryBlock) \
25 if (PyErr_CheckSignals()) { PyTryBlock; } \
28 /* Normalize (remove leading zeros from) a long int object.
29 Doesn't attempt to free the storage--in most cases, due to the nature
30 of the algorithms used, this could save at most be one word anyway. */
33 long_normalize(register PyLongObject
*v
)
35 int j
= ABS(v
->ob_size
);
38 while (i
> 0 && v
->ob_digit
[i
-1] == 0)
41 v
->ob_size
= (v
->ob_size
< 0) ? -(i
) : i
;
45 /* Allocate a new long int object with size digits.
46 Return NULL and set exception if we run out of memory. */
51 return PyObject_NEW_VAR(PyLongObject
, &PyLong_Type
, size
);
55 _PyLong_Copy(PyLongObject
*src
)
64 result
= _PyLong_New(i
);
66 result
->ob_size
= src
->ob_size
;
68 result
->ob_digit
[i
] = src
->ob_digit
[i
];
70 return (PyObject
*)result
;
73 /* Create a new long int object from a C long int */
76 PyLong_FromLong(long ival
)
79 unsigned long t
; /* unsigned so >> doesn't propagate sign bit */
88 /* Count the number of Python digits.
89 We used to pick 5 ("big enough for anything"), but that's a
90 waste of time and space given that 5*15 = 75 bits are rarely
92 t
= (unsigned long)ival
;
97 v
= _PyLong_New(ndigits
);
99 digit
*p
= v
->ob_digit
;
100 v
->ob_size
= negative
? -ndigits
: ndigits
;
101 t
= (unsigned long)ival
;
103 *p
++ = (digit
)(t
& MASK
);
107 return (PyObject
*)v
;
110 /* Create a new long int object from a C unsigned long int */
113 PyLong_FromUnsignedLong(unsigned long ival
)
119 /* Count the number of Python digits. */
120 t
= (unsigned long)ival
;
125 v
= _PyLong_New(ndigits
);
127 digit
*p
= v
->ob_digit
;
128 v
->ob_size
= ndigits
;
130 *p
++ = (digit
)(ival
& MASK
);
134 return (PyObject
*)v
;
137 /* Create a new long int object from a C double */
140 PyLong_FromDouble(double dval
)
144 int i
, ndig
, expo
, neg
;
146 if (Py_IS_INFINITY(dval
)) {
147 PyErr_SetString(PyExc_OverflowError
,
148 "cannot convert float infinity to long");
155 frac
= frexp(dval
, &expo
); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
157 return PyLong_FromLong(0L);
158 ndig
= (expo
-1) / SHIFT
+ 1; /* Number of 'digits' in result */
159 v
= _PyLong_New(ndig
);
162 frac
= ldexp(frac
, (expo
-1) % SHIFT
+ 1);
163 for (i
= ndig
; --i
>= 0; ) {
164 long bits
= (long)frac
;
165 v
->ob_digit
[i
] = (digit
) bits
;
166 frac
= frac
- (double)bits
;
167 frac
= ldexp(frac
, SHIFT
);
170 v
->ob_size
= -(v
->ob_size
);
171 return (PyObject
*)v
;
174 /* Get a C long int from a long int object.
175 Returns -1 and sets an error condition if overflow occurs. */
178 PyLong_AsLong(PyObject
*vv
)
180 /* This version by Tim Peters */
181 register PyLongObject
*v
;
182 unsigned long x
, prev
;
185 if (vv
== NULL
|| !PyLong_Check(vv
)) {
186 if (vv
!= NULL
&& PyInt_Check(vv
))
187 return PyInt_AsLong(vv
);
188 PyErr_BadInternalCall();
191 v
= (PyLongObject
*)vv
;
201 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
202 if ((x
>> SHIFT
) != prev
)
205 /* Haven't lost any bits, but if the sign bit is set we're in
206 * trouble *unless* this is the min negative number. So,
207 * trouble iff sign bit set && (positive || some bit set other
208 * than the sign bit).
210 if ((long)x
< 0 && (sign
> 0 || (x
<< 1) != 0))
212 return (long)x
* sign
;
215 PyErr_SetString(PyExc_OverflowError
,
216 "long int too large to convert to int");
220 /* Get a C long int from a long int object.
221 Returns -1 and sets an error condition if overflow occurs. */
224 PyLong_AsUnsignedLong(PyObject
*vv
)
226 register PyLongObject
*v
;
227 unsigned long x
, prev
;
230 if (vv
== NULL
|| !PyLong_Check(vv
)) {
231 PyErr_BadInternalCall();
232 return (unsigned long) -1;
234 v
= (PyLongObject
*)vv
;
238 PyErr_SetString(PyExc_OverflowError
,
239 "can't convert negative value to unsigned long");
240 return (unsigned long) -1;
244 x
= (x
<< SHIFT
) + v
->ob_digit
[i
];
245 if ((x
>> SHIFT
) != prev
) {
246 PyErr_SetString(PyExc_OverflowError
,
247 "long int too large to convert");
248 return (unsigned long) -1;
255 _PyLong_FromByteArray(const unsigned char* bytes
, size_t n
,
256 int little_endian
, int is_signed
)
258 const unsigned char* pstartbyte
;/* LSB of bytes */
259 int incr
; /* direction to move pstartbyte */
260 const unsigned char* pendbyte
; /* MSB of bytes */
261 size_t numsignificantbytes
; /* number of bytes that matter */
262 size_t ndigits
; /* number of Python long digits */
263 PyLongObject
* v
; /* result */
264 int idigit
= 0; /* next free index in v->ob_digit */
267 return PyLong_FromLong(0L);
271 pendbyte
= bytes
+ n
- 1;
275 pstartbyte
= bytes
+ n
- 1;
281 is_signed
= *pendbyte
>= 0x80;
283 /* Compute numsignificantbytes. This consists of finding the most
284 significant byte. Leading 0 bytes are insignficant if the number
285 is positive, and leading 0xff bytes if negative. */
288 const unsigned char* p
= pendbyte
;
289 const int pincr
= -incr
; /* search MSB to LSB */
290 const unsigned char insignficant
= is_signed
? 0xff : 0x00;
292 for (i
= 0; i
< n
; ++i
, p
+= pincr
) {
293 if (*p
!= insignficant
)
296 numsignificantbytes
= n
- i
;
297 /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
298 actually has 2 significant bytes. OTOH, 0xff0001 ==
299 -0x00ffff, so we wouldn't *need* to bump it there; but we
300 do for 0xffff = -0x0001. To be safe without bothering to
301 check every case, bump it regardless. */
302 if (is_signed
&& numsignificantbytes
< n
)
303 ++numsignificantbytes
;
306 /* How many Python long digits do we need? We have
307 8*numsignificantbytes bits, and each Python long digit has SHIFT
308 bits, so it's the ceiling of the quotient. */
309 ndigits
= (numsignificantbytes
* 8 + SHIFT
- 1) / SHIFT
;
310 if (ndigits
> (size_t)INT_MAX
)
311 return PyErr_NoMemory();
312 v
= _PyLong_New((int)ndigits
);
316 /* Copy the bits over. The tricky parts are computing 2's-comp on
317 the fly for signed numbers, and dealing with the mismatch between
318 8-bit bytes and (probably) 15-bit Python digits.*/
321 twodigits carry
= 1; /* for 2's-comp calculation */
322 twodigits accum
= 0; /* sliding register */
323 unsigned int accumbits
= 0; /* number of bits in accum */
324 const unsigned char* p
= pstartbyte
;
326 for (i
= 0; i
< numsignificantbytes
; ++i
, p
+= incr
) {
327 twodigits thisbyte
= *p
;
328 /* Compute correction for 2's comp, if needed. */
330 thisbyte
= (0xff ^ thisbyte
) + carry
;
331 carry
= thisbyte
>> 8;
334 /* Because we're going LSB to MSB, thisbyte is
335 more significant than what's already in accum,
336 so needs to be prepended to accum. */
337 accum
|= thisbyte
<< accumbits
;
339 if (accumbits
>= SHIFT
) {
340 /* There's enough to fill a Python digit. */
341 assert(idigit
< (int)ndigits
);
342 v
->ob_digit
[idigit
] = (digit
)(accum
& MASK
);
346 assert(accumbits
< SHIFT
);
349 assert(accumbits
< SHIFT
);
351 assert(idigit
< (int)ndigits
);
352 v
->ob_digit
[idigit
] = (digit
)accum
;
357 v
->ob_size
= is_signed
? -idigit
: idigit
;
358 return (PyObject
*)long_normalize(v
);
362 _PyLong_AsByteArray(PyLongObject
* v
,
363 unsigned char* bytes
, size_t n
,
364 int little_endian
, int is_signed
)
366 int i
; /* index into v->ob_digit */
367 int ndigits
; /* |v->ob_size| */
368 twodigits accum
; /* sliding register */
369 unsigned int accumbits
; /* # bits in accum */
370 int do_twos_comp
; /* store 2's-comp? is_signed and v < 0 */
371 twodigits carry
; /* for computing 2's-comp */
372 size_t j
; /* # bytes filled */
373 unsigned char* p
; /* pointer to next byte in bytes */
374 int pincr
; /* direction to move p */
376 assert(v
!= NULL
&& PyLong_Check(v
));
378 if (v
->ob_size
< 0) {
379 ndigits
= -(v
->ob_size
);
381 PyErr_SetString(PyExc_TypeError
,
382 "can't convert negative long to unsigned");
388 ndigits
= v
->ob_size
;
401 /* Copy over all the Python digits.
402 It's crucial that every Python digit except for the MSD contribute
403 exactly SHIFT bits to the total, so first assert that the long is
405 assert(ndigits
== 0 || v
->ob_digit
[ndigits
- 1] != 0);
409 carry
= do_twos_comp
? 1 : 0;
410 for (i
= 0; i
< ndigits
; ++i
) {
411 twodigits thisdigit
= v
->ob_digit
[i
];
413 thisdigit
= (thisdigit
^ MASK
) + carry
;
414 carry
= thisdigit
>> SHIFT
;
417 /* Because we're going LSB to MSB, thisdigit is more
418 significant than what's already in accum, so needs to be
419 prepended to accum. */
420 accum
|= thisdigit
<< accumbits
;
423 /* The most-significant digit may be (probably is) at least
425 if (i
== ndigits
- 1) {
426 /* Count # of sign bits -- they needn't be stored,
427 * although for signed conversion we need later to
428 * make sure at least one sign bit gets stored.
429 * First shift conceptual sign bit to real sign bit.
431 stwodigits s
= (stwodigits
)(thisdigit
<<
432 (8*sizeof(stwodigits
) - SHIFT
));
433 unsigned int nsignbits
= 0;
434 while ((s
< 0) == do_twos_comp
&& nsignbits
< SHIFT
) {
438 accumbits
-= nsignbits
;
441 /* Store as many bytes as possible. */
442 while (accumbits
>= 8) {
446 *p
= (unsigned char)(accum
& 0xff);
453 /* Store the straggler (if any). */
454 assert(accumbits
< 8);
455 assert(carry
== 0); /* else do_twos_comp and *every* digit was 0 */
461 /* Fill leading bits of the byte with sign bits
462 (appropriately pretending that the long had an
463 infinite supply of sign bits). */
464 accum
|= (~(twodigits
)0) << accumbits
;
466 *p
= (unsigned char)(accum
& 0xff);
469 else if (j
== n
&& n
> 0 && is_signed
) {
470 /* The main loop filled the byte array exactly, so the code
471 just above didn't get to ensure there's a sign bit, and the
472 loop below wouldn't add one either. Make sure a sign bit
474 unsigned char msb
= *(p
- pincr
);
475 int sign_bit_set
= msb
>= 0x80;
476 assert(accumbits
== 0);
477 if (sign_bit_set
== do_twos_comp
)
483 /* Fill remaining bytes with copies of the sign bit. */
485 unsigned char signbyte
= do_twos_comp
? 0xffU
: 0U;
486 for ( ; j
< n
; ++j
, p
+= pincr
)
493 PyErr_SetString(PyExc_OverflowError
, "long too big to convert");
499 _PyLong_AsScaledDouble(PyObject
*vv
, int *exponent
)
501 /* NBITS_WANTED should be > the number of bits in a double's precision,
502 but small enough so that 2**NBITS_WANTED is within the normal double
503 range. nbitsneeded is set to 1 less than that because the most-significant
504 Python digit contains at least 1 significant bit, but we don't want to
505 bother counting them (catering to the worst case cheaply).
507 57 is one more than VAX-D double precision; I (Tim) don't know of a double
508 format with more precision than that; it's 1 larger so that we add in at
509 least one round bit to stand in for the ignored least-significant bits.
511 #define NBITS_WANTED 57
514 const double multiplier
= (double)(1L << SHIFT
);
518 if (vv
== NULL
|| !PyLong_Check(vv
)) {
519 PyErr_BadInternalCall();
522 v
= (PyLongObject
*)vv
;
534 x
= (double)v
->ob_digit
[i
];
535 nbitsneeded
= NBITS_WANTED
- 1;
536 /* Invariant: i Python digits remain unaccounted for. */
537 while (i
> 0 && nbitsneeded
> 0) {
539 x
= x
* multiplier
+ (double)v
->ob_digit
[i
];
540 nbitsneeded
-= SHIFT
;
542 /* There are i digits we didn't shift in. Pretending they're all
543 zeroes, the true value is x * 2**(i*SHIFT). */
550 /* Get a C double from a long int object. */
553 PyLong_AsDouble(PyObject
*vv
)
558 if (vv
== NULL
|| !PyLong_Check(vv
)) {
559 PyErr_BadInternalCall();
562 x
= _PyLong_AsScaledDouble(vv
, &e
);
563 if (x
== -1.0 && PyErr_Occurred())
565 if (e
> INT_MAX
/ SHIFT
)
568 x
= ldexp(x
, e
* SHIFT
);
569 if (Py_OVERFLOWED(x
))
574 PyErr_SetString(PyExc_OverflowError
,
575 "long int too large to convert to float");
579 /* Create a new long (or int) object from a C pointer */
582 PyLong_FromVoidPtr(void *p
)
584 #if SIZEOF_VOID_P <= SIZEOF_LONG
585 return PyInt_FromLong((long)p
);
588 #ifndef HAVE_LONG_LONG
589 # error "PyLong_FromVoidPtr: sizeof(void*) > sizeof(long), but no long long"
591 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
592 # error "PyLong_FromVoidPtr: sizeof(LONG_LONG) < sizeof(void*)"
594 /* optimize null pointers */
596 return PyInt_FromLong(0);
597 return PyLong_FromLongLong((LONG_LONG
)p
);
599 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
602 /* Get a C pointer from a long object (or an int object in some cases) */
605 PyLong_AsVoidPtr(PyObject
*vv
)
607 /* This function will allow int or long objects. If vv is neither,
608 then the PyLong_AsLong*() functions will raise the exception:
609 PyExc_SystemError, "bad argument to internal function"
611 #if SIZEOF_VOID_P <= SIZEOF_LONG
615 x
= PyInt_AS_LONG(vv
);
617 x
= PyLong_AsLong(vv
);
620 #ifndef HAVE_LONG_LONG
621 # error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
623 #if SIZEOF_LONG_LONG < SIZEOF_VOID_P
624 # error "PyLong_AsVoidPtr: sizeof(LONG_LONG) < sizeof(void*)"
629 x
= PyInt_AS_LONG(vv
);
631 x
= PyLong_AsLongLong(vv
);
633 #endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
635 if (x
== -1 && PyErr_Occurred())
640 #ifdef HAVE_LONG_LONG
642 /* Initial LONG_LONG support by Chris Herborth (chrish@qnx.com), later
643 * rewritten to use the newer PyLong_{As,From}ByteArray API.
646 #define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
648 /* Create a new long int object from a C LONG_LONG int. */
651 PyLong_FromLongLong(LONG_LONG ival
)
653 LONG_LONG bytes
= ival
;
655 return _PyLong_FromByteArray(
656 (unsigned char *)&bytes
,
657 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
660 /* Create a new long int object from a C unsigned LONG_LONG int. */
663 PyLong_FromUnsignedLongLong(unsigned LONG_LONG ival
)
665 unsigned LONG_LONG bytes
= ival
;
667 return _PyLong_FromByteArray(
668 (unsigned char *)&bytes
,
669 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
672 /* Get a C LONG_LONG int from a long int object.
673 Return -1 and set an error if overflow occurs. */
676 PyLong_AsLongLong(PyObject
*vv
)
683 PyErr_BadInternalCall();
686 if (!PyLong_Check(vv
)) {
688 return (LONG_LONG
)PyInt_AsLong(vv
);
689 PyErr_BadInternalCall();
693 res
= _PyLong_AsByteArray(
694 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
695 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 1);
697 return res
< 0 ? (LONG_LONG
)res
: bytes
;
700 /* Get a C unsigned LONG_LONG int from a long int object.
701 Return -1 and set an error if overflow occurs. */
704 PyLong_AsUnsignedLongLong(PyObject
*vv
)
706 unsigned LONG_LONG bytes
;
710 if (vv
== NULL
|| !PyLong_Check(vv
)) {
711 PyErr_BadInternalCall();
715 res
= _PyLong_AsByteArray(
716 (PyLongObject
*)vv
, (unsigned char *)&bytes
,
717 SIZEOF_LONG_LONG
, IS_LITTLE_ENDIAN
, 0);
719 return res
< 0 ? (unsigned LONG_LONG
)res
: bytes
;
722 #undef IS_LITTLE_ENDIAN
724 #endif /* HAVE_LONG_LONG */
728 convert_binop(PyObject
*v
, PyObject
*w
, PyLongObject
**a
, PyLongObject
**b
) {
729 if (PyLong_Check(v
)) {
730 *a
= (PyLongObject
*) v
;
733 else if (PyInt_Check(v
)) {
734 *a
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(v
));
739 if (PyLong_Check(w
)) {
740 *b
= (PyLongObject
*) w
;
743 else if (PyInt_Check(w
)) {
744 *b
= (PyLongObject
*) PyLong_FromLong(PyInt_AS_LONG(w
));
753 #define CONVERT_BINOP(v, w, a, b) \
754 if (!convert_binop(v, w, a, b)) { \
755 Py_INCREF(Py_NotImplemented); \
756 return Py_NotImplemented; \
760 /* Multiply by a single digit, ignoring the sign. */
762 static PyLongObject
*
763 mul1(PyLongObject
*a
, wdigit n
)
765 return muladd1(a
, n
, (digit
)0);
768 /* Multiply by a single digit and add a single digit, ignoring the sign. */
770 static PyLongObject
*
771 muladd1(PyLongObject
*a
, wdigit n
, wdigit extra
)
773 int size_a
= ABS(a
->ob_size
);
774 PyLongObject
*z
= _PyLong_New(size_a
+1);
775 twodigits carry
= extra
;
780 for (i
= 0; i
< size_a
; ++i
) {
781 carry
+= (twodigits
)a
->ob_digit
[i
] * n
;
782 z
->ob_digit
[i
] = (digit
) (carry
& MASK
);
785 z
->ob_digit
[i
] = (digit
) carry
;
786 return long_normalize(z
);
789 /* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
790 in pout, and returning the remainder. pin and pout point at the LSD.
791 It's OK for pin == pout on entry, which saves oodles of mallocs/frees in
792 long_format, but that should be done with great care since longs are
796 inplace_divrem1(digit
*pout
, digit
*pin
, int size
, digit n
)
800 assert(n
> 0 && n
<= MASK
);
803 while (--size
>= 0) {
805 rem
= (rem
<< SHIFT
) + *--pin
;
806 *--pout
= hi
= (digit
)(rem
/ n
);
812 /* Divide a long integer by a digit, returning both the quotient
813 (as function result) and the remainder (through *prem).
814 The sign of a is ignored; n should not be zero. */
816 static PyLongObject
*
817 divrem1(PyLongObject
*a
, digit n
, digit
*prem
)
819 const int size
= ABS(a
->ob_size
);
822 assert(n
> 0 && n
<= MASK
);
823 z
= _PyLong_New(size
);
826 *prem
= inplace_divrem1(z
->ob_digit
, a
->ob_digit
, size
, n
);
827 return long_normalize(z
);
830 /* Convert a long int object to a string, using a given conversion base.
831 Return a string object.
832 If base is 8 or 16, add the proper prefix '0' or '0x'. */
835 long_format(PyObject
*aa
, int base
, int addL
)
837 register PyLongObject
*a
= (PyLongObject
*)aa
;
840 const int size_a
= ABS(a
->ob_size
);
845 if (a
== NULL
|| !PyLong_Check(a
)) {
846 PyErr_BadInternalCall();
849 assert(base
>= 2 && base
<= 36);
851 /* Compute a rough upper bound for the length of the string */
858 i
= 5 + (addL
? 1 : 0) + (size_a
*SHIFT
+ bits
-1) / bits
;
859 str
= (PyStringObject
*) PyString_FromStringAndSize((char *)0, i
);
862 p
= PyString_AS_STRING(str
) + i
;
869 if (a
->ob_size
== 0) {
872 else if ((base
& (base
- 1)) == 0) {
873 /* JRH: special case for power-of-2 bases */
875 int accumbits
= 0; /* # of bits in accum */
876 int basebits
= 1; /* # of bits in base-1 */
878 while ((i
>>= 1) > 1)
881 for (i
= 0; i
< size_a
; ++i
) {
882 accum
|= a
->ob_digit
[i
] << accumbits
;
884 assert(accumbits
>= basebits
);
886 char cdigit
= (char)(accum
& (base
- 1));
887 cdigit
+= (cdigit
< 10) ? '0' : 'A'-10;
888 assert(p
> PyString_AS_STRING(str
));
890 accumbits
-= basebits
;
892 } while (i
< size_a
-1 ? accumbits
>= basebits
:
897 /* Not 0, and base not a power of 2. Divide repeatedly by
898 base, but for speed use the highest power of base that
901 digit
*pin
= a
->ob_digit
;
902 PyLongObject
*scratch
;
903 /* powbasw <- largest power of base that fits in a digit. */
904 digit powbase
= base
; /* powbase == base ** power */
907 unsigned long newpow
= powbase
* (unsigned long)base
;
908 if (newpow
>> SHIFT
) /* doesn't fit in a digit */
910 powbase
= (digit
)newpow
;
914 /* Get a scratch area for repeated division. */
915 scratch
= _PyLong_New(size
);
916 if (scratch
== NULL
) {
921 /* Repeatedly divide by powbase. */
923 int ntostore
= power
;
924 digit rem
= inplace_divrem1(scratch
->ob_digit
,
926 pin
= scratch
->ob_digit
; /* no need to use a again */
927 if (pin
[size
- 1] == 0)
935 /* Break rem into digits. */
936 assert(ntostore
> 0);
938 digit nextrem
= (digit
)(rem
/ base
);
939 char c
= (char)(rem
- nextrem
* base
);
940 assert(p
> PyString_AS_STRING(str
));
941 c
+= (c
< 10) ? '0' : 'A'-10;
945 /* Termination is a bit delicate: must not
946 store leading zeroes, so must get out if
947 remaining quotient and rem are both 0. */
948 } while (ntostore
&& (size
|| rem
));
957 else if (base
== 16) {
961 else if (base
!= 10) {
963 *--p
= '0' + base
%10;
965 *--p
= '0' + base
/10;
969 if (p
!= PyString_AS_STRING(str
)) {
970 char *q
= PyString_AS_STRING(str
);
973 } while ((*q
++ = *p
++) != '\0');
975 _PyString_Resize((PyObject
**)&str
,
976 (int) (q
- PyString_AS_STRING(str
)));
978 return (PyObject
*)str
;
982 PyLong_FromString(char *str
, char **pend
, int base
)
985 char *start
, *orig_str
= str
;
988 if ((base
!= 0 && base
< 2) || base
> 36) {
989 PyErr_SetString(PyExc_ValueError
,
990 "long() arg 2 must be >= 2 and <= 36");
993 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
997 else if (*str
== '-') {
1001 while (*str
!= '\0' && isspace(Py_CHARMASK(*str
)))
1006 else if (str
[1] == 'x' || str
[1] == 'X')
1011 if (base
== 16 && str
[0] == '0' && (str
[1] == 'x' || str
[1] == 'X'))
1015 for ( ; z
!= NULL
; ++str
) {
1021 else if (*str
>= 'a')
1022 k
= *str
- 'a' + 10;
1023 else if (*str
>= 'A')
1024 k
= *str
- 'A' + 10;
1025 if (k
< 0 || k
>= base
)
1027 temp
= muladd1(z
, (digit
)base
, (digit
)k
);
1035 if (sign
< 0 && z
!= NULL
&& z
->ob_size
!= 0)
1036 z
->ob_size
= -(z
->ob_size
);
1037 if (*str
== 'L' || *str
== 'l')
1039 while (*str
&& isspace(Py_CHARMASK(*str
)))
1045 return (PyObject
*) z
;
1048 PyErr_Format(PyExc_ValueError
,
1049 "invalid literal for long(): %.200s", orig_str
);
1054 #ifdef Py_USING_UNICODE
1056 PyLong_FromUnicode(Py_UNICODE
*u
, int length
, int base
)
1060 if (length
>= sizeof(buffer
)) {
1061 PyErr_SetString(PyExc_ValueError
,
1062 "long() literal too large to convert");
1065 if (PyUnicode_EncodeDecimal(u
, length
, buffer
, NULL
))
1068 return PyLong_FromString(buffer
, NULL
, base
);
1073 static PyLongObject
*x_divrem
1074 (PyLongObject
*, PyLongObject
*, PyLongObject
**);
1075 static PyObject
*long_pos(PyLongObject
*);
1076 static int long_divrem(PyLongObject
*, PyLongObject
*,
1077 PyLongObject
**, PyLongObject
**);
1079 /* Long division with remainder, top-level routine */
1082 long_divrem(PyLongObject
*a
, PyLongObject
*b
,
1083 PyLongObject
**pdiv
, PyLongObject
**prem
)
1085 int size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1089 PyErr_SetString(PyExc_ZeroDivisionError
,
1090 "long division or modulo by zero");
1093 if (size_a
< size_b
||
1094 (size_a
== size_b
&&
1095 a
->ob_digit
[size_a
-1] < b
->ob_digit
[size_b
-1])) {
1097 *pdiv
= _PyLong_New(0);
1099 *prem
= (PyLongObject
*) a
;
1104 z
= divrem1(a
, b
->ob_digit
[0], &rem
);
1107 *prem
= (PyLongObject
*) PyLong_FromLong((long)rem
);
1110 z
= x_divrem(a
, b
, prem
);
1115 The quotient z has the sign of a*b;
1116 the remainder r has the sign of a,
1118 if ((a
->ob_size
< 0) != (b
->ob_size
< 0))
1119 z
->ob_size
= -(z
->ob_size
);
1120 if (a
->ob_size
< 0 && (*prem
)->ob_size
!= 0)
1121 (*prem
)->ob_size
= -((*prem
)->ob_size
);
1126 /* Unsigned long division with remainder -- the algorithm */
1128 static PyLongObject
*
1129 x_divrem(PyLongObject
*v1
, PyLongObject
*w1
, PyLongObject
**prem
)
1131 int size_v
= ABS(v1
->ob_size
), size_w
= ABS(w1
->ob_size
);
1132 digit d
= (digit
) ((twodigits
)BASE
/ (w1
->ob_digit
[size_w
-1] + 1));
1133 PyLongObject
*v
= mul1(v1
, d
);
1134 PyLongObject
*w
= mul1(w1
, d
);
1138 if (v
== NULL
|| w
== NULL
) {
1144 assert(size_v
>= size_w
&& size_w
> 1); /* Assert checks by div() */
1145 assert(v
->ob_refcnt
== 1); /* Since v will be used as accumulator! */
1146 assert(size_w
== ABS(w
->ob_size
)); /* That's how d was calculated */
1148 size_v
= ABS(v
->ob_size
);
1149 a
= _PyLong_New(size_v
- size_w
+ 1);
1151 for (j
= size_v
, k
= a
->ob_size
-1; a
!= NULL
&& k
>= 0; --j
, --k
) {
1152 digit vj
= (j
>= size_v
) ? 0 : v
->ob_digit
[j
];
1154 stwodigits carry
= 0;
1162 if (vj
== w
->ob_digit
[size_w
-1])
1165 q
= (((twodigits
)vj
<< SHIFT
) + v
->ob_digit
[j
-1]) /
1166 w
->ob_digit
[size_w
-1];
1168 while (w
->ob_digit
[size_w
-2]*q
>
1170 ((twodigits
)vj
<< SHIFT
)
1172 - q
*w
->ob_digit
[size_w
-1]
1177 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1178 twodigits z
= w
->ob_digit
[i
] * q
;
1179 digit zz
= (digit
) (z
>> SHIFT
);
1180 carry
+= v
->ob_digit
[i
+k
] - z
1181 + ((twodigits
)zz
<< SHIFT
);
1182 v
->ob_digit
[i
+k
] = carry
& MASK
;
1183 carry
= Py_ARITHMETIC_RIGHT_SHIFT(BASE_TWODIGITS_TYPE
,
1189 carry
+= v
->ob_digit
[i
+k
];
1190 v
->ob_digit
[i
+k
] = 0;
1194 a
->ob_digit
[k
] = (digit
) q
;
1196 assert(carry
== -1);
1197 a
->ob_digit
[k
] = (digit
) q
-1;
1199 for (i
= 0; i
< size_w
&& i
+k
< size_v
; ++i
) {
1200 carry
+= v
->ob_digit
[i
+k
] + w
->ob_digit
[i
];
1201 v
->ob_digit
[i
+k
] = carry
& MASK
;
1202 carry
= Py_ARITHMETIC_RIGHT_SHIFT(
1203 BASE_TWODIGITS_TYPE
,
1212 a
= long_normalize(a
);
1213 *prem
= divrem1(v
, d
, &d
);
1214 /* d receives the (unused) remainder */
1215 if (*prem
== NULL
) {
1228 long_dealloc(PyObject
*v
)
1230 v
->ob_type
->tp_free(v
);
1234 long_repr(PyObject
*v
)
1236 return long_format(v
, 10, 1);
1240 long_str(PyObject
*v
)
1242 return long_format(v
, 10, 0);
1246 long_compare(PyLongObject
*a
, PyLongObject
*b
)
1250 if (a
->ob_size
!= b
->ob_size
) {
1251 if (ABS(a
->ob_size
) == 0 && ABS(b
->ob_size
) == 0)
1254 sign
= a
->ob_size
- b
->ob_size
;
1257 int i
= ABS(a
->ob_size
);
1258 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
1263 sign
= (int)a
->ob_digit
[i
] - (int)b
->ob_digit
[i
];
1268 return sign
< 0 ? -1 : sign
> 0 ? 1 : 0;
1272 long_hash(PyLongObject
*v
)
1277 /* This is designed so that Python ints and longs with the
1278 same value hash to the same value, otherwise comparisons
1279 of mapping keys will turn out weird */
1288 /* Force a 32-bit circular shift */
1289 x
= ((x
<< SHIFT
) & ~MASK
) | ((x
>> (32-SHIFT
)) & MASK
);
1290 x
+= v
->ob_digit
[i
];
1299 /* Add the absolute values of two long integers. */
1301 static PyLongObject
*
1302 x_add(PyLongObject
*a
, PyLongObject
*b
)
1304 int size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1309 /* Ensure a is the larger of the two: */
1310 if (size_a
< size_b
) {
1311 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1312 { int size_temp
= size_a
;
1314 size_b
= size_temp
; }
1316 z
= _PyLong_New(size_a
+1);
1319 for (i
= 0; i
< size_b
; ++i
) {
1320 carry
+= a
->ob_digit
[i
] + b
->ob_digit
[i
];
1321 z
->ob_digit
[i
] = carry
& MASK
;
1324 for (; i
< size_a
; ++i
) {
1325 carry
+= a
->ob_digit
[i
];
1326 z
->ob_digit
[i
] = carry
& MASK
;
1329 z
->ob_digit
[i
] = carry
;
1330 return long_normalize(z
);
1333 /* Subtract the absolute values of two integers. */
1335 static PyLongObject
*
1336 x_sub(PyLongObject
*a
, PyLongObject
*b
)
1338 int size_a
= ABS(a
->ob_size
), size_b
= ABS(b
->ob_size
);
1344 /* Ensure a is the larger of the two: */
1345 if (size_a
< size_b
) {
1347 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1348 { int size_temp
= size_a
;
1350 size_b
= size_temp
; }
1352 else if (size_a
== size_b
) {
1353 /* Find highest digit where a and b differ: */
1355 while (--i
>= 0 && a
->ob_digit
[i
] == b
->ob_digit
[i
])
1358 return _PyLong_New(0);
1359 if (a
->ob_digit
[i
] < b
->ob_digit
[i
]) {
1361 { PyLongObject
*temp
= a
; a
= b
; b
= temp
; }
1363 size_a
= size_b
= i
+1;
1365 z
= _PyLong_New(size_a
);
1368 for (i
= 0; i
< size_b
; ++i
) {
1369 /* The following assumes unsigned arithmetic
1370 works module 2**N for some N>SHIFT. */
1371 borrow
= a
->ob_digit
[i
] - b
->ob_digit
[i
] - borrow
;
1372 z
->ob_digit
[i
] = borrow
& MASK
;
1374 borrow
&= 1; /* Keep only one sign bit */
1376 for (; i
< size_a
; ++i
) {
1377 borrow
= a
->ob_digit
[i
] - borrow
;
1378 z
->ob_digit
[i
] = borrow
& MASK
;
1380 borrow
&= 1; /* Keep only one sign bit */
1382 assert(borrow
== 0);
1384 z
->ob_size
= -(z
->ob_size
);
1385 return long_normalize(z
);
1389 long_add(PyLongObject
*v
, PyLongObject
*w
)
1391 PyLongObject
*a
, *b
, *z
;
1393 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
1395 if (a
->ob_size
< 0) {
1396 if (b
->ob_size
< 0) {
1398 if (z
!= NULL
&& z
->ob_size
!= 0)
1399 z
->ob_size
= -(z
->ob_size
);
1412 return (PyObject
*)z
;
1416 long_sub(PyLongObject
*v
, PyLongObject
*w
)
1418 PyLongObject
*a
, *b
, *z
;
1420 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
1422 if (a
->ob_size
< 0) {
1427 if (z
!= NULL
&& z
->ob_size
!= 0)
1428 z
->ob_size
= -(z
->ob_size
);
1438 return (PyObject
*)z
;
1442 long_repeat(PyObject
*v
, PyLongObject
*w
)
1444 /* sequence * long */
1445 long n
= PyLong_AsLong((PyObject
*) w
);
1446 if (n
== -1 && PyErr_Occurred())
1449 return (*v
->ob_type
->tp_as_sequence
->sq_repeat
)(v
, n
);
1453 long_mul(PyLongObject
*v
, PyLongObject
*w
)
1455 PyLongObject
*a
, *b
, *z
;
1460 if (!convert_binop((PyObject
*)v
, (PyObject
*)w
, &a
, &b
)) {
1461 if (!PyLong_Check(v
) &&
1462 v
->ob_type
->tp_as_sequence
&&
1463 v
->ob_type
->tp_as_sequence
->sq_repeat
)
1464 return long_repeat((PyObject
*)v
, w
);
1465 if (!PyLong_Check(w
) &&
1466 w
->ob_type
->tp_as_sequence
&&
1467 w
->ob_type
->tp_as_sequence
->sq_repeat
)
1468 return long_repeat((PyObject
*)w
, v
);
1469 Py_INCREF(Py_NotImplemented
);
1470 return Py_NotImplemented
;
1473 size_a
= ABS(a
->ob_size
);
1474 size_b
= ABS(b
->ob_size
);
1475 if (size_a
> size_b
) {
1476 /* we are faster with the small object on the left */
1477 int hold_sa
= size_a
;
1478 PyLongObject
*hold_a
= a
;
1484 z
= _PyLong_New(size_a
+ size_b
);
1490 for (i
= 0; i
< z
->ob_size
; ++i
)
1492 for (i
= 0; i
< size_a
; ++i
) {
1493 twodigits carry
= 0;
1494 twodigits f
= a
->ob_digit
[i
];
1503 for (j
= 0; j
< size_b
; ++j
) {
1504 carry
+= z
->ob_digit
[i
+j
] + b
->ob_digit
[j
] * f
;
1505 z
->ob_digit
[i
+j
] = (digit
) (carry
& MASK
);
1508 for (; carry
!= 0; ++j
) {
1509 assert(i
+j
< z
->ob_size
);
1510 carry
+= z
->ob_digit
[i
+j
];
1511 z
->ob_digit
[i
+j
] = (digit
) (carry
& MASK
);
1516 z
->ob_size
= -(z
->ob_size
);
1518 z
->ob_size
= -(z
->ob_size
);
1521 return (PyObject
*) long_normalize(z
);
1524 /* The / and % operators are now defined in terms of divmod().
1525 The expression a mod b has the value a - b*floor(a/b).
1526 The long_divrem function gives the remainder after division of
1527 |a| by |b|, with the sign of a. This is also expressed
1528 as a - b*trunc(a/b), if trunc truncates towards zero.
1535 So, to get from rem to mod, we have to add b if a and b
1536 have different signs. We then subtract one from the 'div'
1537 part of the outcome to keep the invariant intact. */
1540 l_divmod(PyLongObject
*v
, PyLongObject
*w
,
1541 PyLongObject
**pdiv
, PyLongObject
**pmod
)
1543 PyLongObject
*div
, *mod
;
1545 if (long_divrem(v
, w
, &div
, &mod
) < 0)
1547 if ((mod
->ob_size
< 0 && w
->ob_size
> 0) ||
1548 (mod
->ob_size
> 0 && w
->ob_size
< 0)) {
1551 temp
= (PyLongObject
*) long_add(mod
, w
);
1558 one
= (PyLongObject
*) PyLong_FromLong(1L);
1560 (temp
= (PyLongObject
*) long_sub(div
, one
)) == NULL
) {
1576 long_div(PyObject
*v
, PyObject
*w
)
1578 PyLongObject
*a
, *b
, *div
, *mod
;
1580 CONVERT_BINOP(v
, w
, &a
, &b
);
1582 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
1590 return (PyObject
*)div
;
1594 long_classic_div(PyObject
*v
, PyObject
*w
)
1596 PyLongObject
*a
, *b
, *div
, *mod
;
1598 CONVERT_BINOP(v
, w
, &a
, &b
);
1600 if (Py_DivisionWarningFlag
&&
1601 PyErr_Warn(PyExc_DeprecationWarning
, "classic long division") < 0)
1603 else if (l_divmod(a
, b
, &div
, &mod
) < 0)
1610 return (PyObject
*)div
;
1614 long_true_divide(PyObject
*v
, PyObject
*w
)
1616 PyLongObject
*a
, *b
;
1618 int aexp
, bexp
, failed
;
1620 CONVERT_BINOP(v
, w
, &a
, &b
);
1621 ad
= _PyLong_AsScaledDouble((PyObject
*)a
, &aexp
);
1622 bd
= _PyLong_AsScaledDouble((PyObject
*)b
, &bexp
);
1623 failed
= (ad
== -1.0 || bd
== -1.0) && PyErr_Occurred();
1630 PyErr_SetString(PyExc_ZeroDivisionError
,
1631 "long division or modulo by zero");
1635 /* True value is very close to ad/bd * 2**(SHIFT*(aexp-bexp)) */
1636 ad
/= bd
; /* overflow/underflow impossible here */
1638 if (aexp
> INT_MAX
/ SHIFT
)
1640 else if (aexp
< -(INT_MAX
/ SHIFT
))
1641 return PyFloat_FromDouble(0.0); /* underflow to 0 */
1643 ad
= ldexp(ad
, aexp
* SHIFT
);
1644 if (Py_OVERFLOWED(ad
)) /* ignore underflow to 0.0 */
1646 return PyFloat_FromDouble(ad
);
1649 PyErr_SetString(PyExc_OverflowError
,
1650 "long/long too large for a float");
1656 long_mod(PyObject
*v
, PyObject
*w
)
1658 PyLongObject
*a
, *b
, *div
, *mod
;
1660 CONVERT_BINOP(v
, w
, &a
, &b
);
1662 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
1670 return (PyObject
*)mod
;
1674 long_divmod(PyObject
*v
, PyObject
*w
)
1676 PyLongObject
*a
, *b
, *div
, *mod
;
1679 CONVERT_BINOP(v
, w
, &a
, &b
);
1681 if (l_divmod(a
, b
, &div
, &mod
) < 0) {
1688 PyTuple_SetItem(z
, 0, (PyObject
*) div
);
1689 PyTuple_SetItem(z
, 1, (PyObject
*) mod
);
1701 long_pow(PyObject
*v
, PyObject
*w
, PyObject
*x
)
1703 PyLongObject
*a
, *b
;
1705 PyLongObject
*z
, *div
, *mod
;
1708 CONVERT_BINOP(v
, w
, &a
, &b
);
1709 if (PyLong_Check(x
) || Py_None
== x
) {
1713 else if (PyInt_Check(x
)) {
1714 c
= PyLong_FromLong(PyInt_AS_LONG(x
));
1719 Py_INCREF(Py_NotImplemented
);
1720 return Py_NotImplemented
;
1723 if (c
!= Py_None
&& ((PyLongObject
*)c
)->ob_size
== 0) {
1724 PyErr_SetString(PyExc_ValueError
,
1725 "pow() 3rd argument cannot be 0");
1730 size_b
= b
->ob_size
;
1736 PyErr_SetString(PyExc_TypeError
, "pow() 2nd argument "
1737 "cannot be negative when 3rd argument specified");
1740 /* Return a float. This works because we know that
1741 this calls float_pow() which converts its
1742 arguments to double. */
1743 return PyFloat_Type
.tp_as_number
->nb_power(v
, w
, x
);
1745 z
= (PyLongObject
*)PyLong_FromLong(1L);
1746 for (i
= 0; i
< size_b
; ++i
) {
1747 digit bi
= b
->ob_digit
[i
];
1750 for (j
= 0; j
< SHIFT
; ++j
) {
1754 temp
= (PyLongObject
*)long_mul(z
, a
);
1756 if (c
!=Py_None
&& temp
!=NULL
) {
1757 if (l_divmod(temp
,(PyLongObject
*)c
,
1772 if (bi
== 0 && i
+1 == size_b
)
1774 temp
= (PyLongObject
*)long_mul(a
, a
);
1776 if (c
!=Py_None
&& temp
!=NULL
) {
1777 if (l_divmod(temp
, (PyLongObject
*)c
, &div
,
1794 if (a
== NULL
|| z
== NULL
)
1797 if (c
!=Py_None
&& z
!=NULL
) {
1798 if (l_divmod(z
, (PyLongObject
*)c
, &div
, &mod
) < 0) {
1812 return (PyObject
*)z
;
1816 long_invert(PyLongObject
*v
)
1818 /* Implement ~x as -(x+1) */
1821 w
= (PyLongObject
*)PyLong_FromLong(1L);
1824 x
= (PyLongObject
*) long_add(v
, w
);
1828 x
->ob_size
= -(x
->ob_size
);
1829 return (PyObject
*)x
;
1833 long_pos(PyLongObject
*v
)
1835 if (PyLong_CheckExact(v
)) {
1837 return (PyObject
*)v
;
1840 return _PyLong_Copy(v
);
1844 long_neg(PyLongObject
*v
)
1847 if (v
->ob_size
== 0 && PyLong_CheckExact(v
)) {
1850 return (PyObject
*) v
;
1852 z
= (PyLongObject
*)_PyLong_Copy(v
);
1854 z
->ob_size
= -(v
->ob_size
);
1855 return (PyObject
*)z
;
1859 long_abs(PyLongObject
*v
)
1868 long_nonzero(PyLongObject
*v
)
1870 return ABS(v
->ob_size
) != 0;
1874 long_rshift(PyLongObject
*v
, PyLongObject
*w
)
1876 PyLongObject
*a
, *b
;
1877 PyLongObject
*z
= NULL
;
1879 int newsize
, wordshift
, loshift
, hishift
, i
, j
;
1880 digit lomask
, himask
;
1882 CONVERT_BINOP((PyObject
*)v
, (PyObject
*)w
, &a
, &b
);
1884 if (a
->ob_size
< 0) {
1885 /* Right shifting negative numbers is harder */
1886 PyLongObject
*a1
, *a2
;
1887 a1
= (PyLongObject
*) long_invert(a
);
1890 a2
= (PyLongObject
*) long_rshift(a1
, b
);
1894 z
= (PyLongObject
*) long_invert(a2
);
1899 shiftby
= PyLong_AsLong((PyObject
*)b
);
1900 if (shiftby
== -1L && PyErr_Occurred())
1903 PyErr_SetString(PyExc_ValueError
,
1904 "negative shift count");
1907 wordshift
= shiftby
/ SHIFT
;
1908 newsize
= ABS(a
->ob_size
) - wordshift
;
1913 return (PyObject
*)z
;
1915 loshift
= shiftby
% SHIFT
;
1916 hishift
= SHIFT
- loshift
;
1917 lomask
= ((digit
)1 << hishift
) - 1;
1918 himask
= MASK
^ lomask
;
1919 z
= _PyLong_New(newsize
);
1923 z
->ob_size
= -(z
->ob_size
);
1924 for (i
= 0, j
= wordshift
; i
< newsize
; i
++, j
++) {
1925 z
->ob_digit
[i
] = (a
->ob_digit
[j
] >> loshift
) & lomask
;
1928 (a
->ob_digit
[j
+1] << hishift
) & himask
;
1930 z
= long_normalize(z
);
1935 return (PyObject
*) z
;
1940 long_lshift(PyObject
*v
, PyObject
*w
)
1942 /* This version due to Tim Peters */
1943 PyLongObject
*a
, *b
;
1944 PyLongObject
*z
= NULL
;
1946 int oldsize
, newsize
, wordshift
, remshift
, i
, j
;
1949 CONVERT_BINOP(v
, w
, &a
, &b
);
1951 shiftby
= PyLong_AsLong((PyObject
*)b
);
1952 if (shiftby
== -1L && PyErr_Occurred())
1955 PyErr_SetString(PyExc_ValueError
, "negative shift count");
1958 if ((long)(int)shiftby
!= shiftby
) {
1959 PyErr_SetString(PyExc_ValueError
,
1960 "outrageous left shift count");
1963 /* wordshift, remshift = divmod(shiftby, SHIFT) */
1964 wordshift
= (int)shiftby
/ SHIFT
;
1965 remshift
= (int)shiftby
- wordshift
* SHIFT
;
1967 oldsize
= ABS(a
->ob_size
);
1968 newsize
= oldsize
+ wordshift
;
1971 z
= _PyLong_New(newsize
);
1975 z
->ob_size
= -(z
->ob_size
);
1976 for (i
= 0; i
< wordshift
; i
++)
1979 for (i
= wordshift
, j
= 0; j
< oldsize
; i
++, j
++) {
1980 accum
|= a
->ob_digit
[j
] << remshift
;
1981 z
->ob_digit
[i
] = (digit
)(accum
& MASK
);
1985 z
->ob_digit
[newsize
-1] = (digit
)accum
;
1988 z
= long_normalize(z
);
1992 return (PyObject
*) z
;
1996 /* Bitwise and/xor/or operations */
1998 #define MAX(x, y) ((x) < (y) ? (y) : (x))
1999 #define MIN(x, y) ((x) > (y) ? (y) : (x))
2002 long_bitwise(PyLongObject
*a
,
2003 int op
, /* '&', '|', '^' */
2006 digit maska
, maskb
; /* 0 or MASK */
2008 int size_a
, size_b
, size_z
;
2014 if (a
->ob_size
< 0) {
2015 a
= (PyLongObject
*) long_invert(a
);
2022 if (b
->ob_size
< 0) {
2023 b
= (PyLongObject
*) long_invert(b
);
2034 if (maska
!= maskb
) {
2040 if (maska
&& maskb
) {
2048 if (maska
|| maskb
) {
2057 /* JRH: The original logic here was to allocate the result value (z)
2058 as the longer of the two operands. However, there are some cases
2059 where the result is guaranteed to be shorter than that: AND of two
2060 positives, OR of two negatives: use the shorter number. AND with
2061 mixed signs: use the positive number. OR with mixed signs: use the
2062 negative number. After the transformations above, op will be '&'
2063 iff one of these cases applies, and mask will be non-0 for operands
2064 whose length should be ignored.
2067 size_a
= a
->ob_size
;
2068 size_b
= b
->ob_size
;
2072 : (maskb
? size_a
: MIN(size_a
, size_b
)))
2073 : MAX(size_a
, size_b
);
2074 z
= _PyLong_New(size_z
);
2075 if (a
== NULL
|| b
== NULL
|| z
== NULL
) {
2082 for (i
= 0; i
< size_z
; ++i
) {
2083 diga
= (i
< size_a
? a
->ob_digit
[i
] : 0) ^ maska
;
2084 digb
= (i
< size_b
? b
->ob_digit
[i
] : 0) ^ maskb
;
2086 case '&': z
->ob_digit
[i
] = diga
& digb
; break;
2087 case '|': z
->ob_digit
[i
] = diga
| digb
; break;
2088 case '^': z
->ob_digit
[i
] = diga
^ digb
; break;
2094 z
= long_normalize(z
);
2096 return (PyObject
*) z
;
2103 long_and(PyObject
*v
, PyObject
*w
)
2105 PyLongObject
*a
, *b
;
2107 CONVERT_BINOP(v
, w
, &a
, &b
);
2108 c
= long_bitwise(a
, '&', b
);
2115 long_xor(PyObject
*v
, PyObject
*w
)
2117 PyLongObject
*a
, *b
;
2119 CONVERT_BINOP(v
, w
, &a
, &b
);
2120 c
= long_bitwise(a
, '^', b
);
2127 long_or(PyObject
*v
, PyObject
*w
)
2129 PyLongObject
*a
, *b
;
2131 CONVERT_BINOP(v
, w
, &a
, &b
);
2132 c
= long_bitwise(a
, '|', b
);
2139 long_coerce(PyObject
**pv
, PyObject
**pw
)
2141 if (PyInt_Check(*pw
)) {
2142 *pw
= PyLong_FromLong(PyInt_AS_LONG(*pw
));
2146 else if (PyLong_Check(*pw
)) {
2151 return 1; /* Can't do it */
2155 long_int(PyObject
*v
)
2158 x
= PyLong_AsLong(v
);
2159 if (PyErr_Occurred())
2161 return PyInt_FromLong(x
);
2165 long_long(PyObject
*v
)
2172 long_float(PyObject
*v
)
2175 result
= PyLong_AsDouble(v
);
2176 if (result
== -1.0 && PyErr_Occurred())
2178 return PyFloat_FromDouble(result
);
2182 long_oct(PyObject
*v
)
2184 return long_format(v
, 8, 1);
2188 long_hex(PyObject
*v
)
2190 return long_format(v
, 16, 1);
2192 staticforward PyObject
*
2193 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
);
2196 long_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2199 int base
= -909; /* unlikely! */
2200 static char *kwlist
[] = {"x", "base", 0};
2202 if (type
!= &PyLong_Type
)
2203 return long_subtype_new(type
, args
, kwds
); /* Wimp out */
2204 if (!PyArg_ParseTupleAndKeywords(args
, kwds
, "|Oi:long", kwlist
,
2208 return PyLong_FromLong(0L);
2210 return PyNumber_Long(x
);
2211 else if (PyString_Check(x
))
2212 return PyLong_FromString(PyString_AS_STRING(x
), NULL
, base
);
2213 #ifdef Py_USING_UNICODE
2214 else if (PyUnicode_Check(x
))
2215 return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x
),
2216 PyUnicode_GET_SIZE(x
),
2220 PyErr_SetString(PyExc_TypeError
,
2221 "long() can't convert non-string with explicit base");
2226 /* Wimpy, slow approach to tp_new calls for subtypes of long:
2227 first create a regular long from whatever arguments we got,
2228 then allocate a subtype instance and initialize it from
2229 the regular long. The regular long is then thrown away.
2232 long_subtype_new(PyTypeObject
*type
, PyObject
*args
, PyObject
*kwds
)
2234 PyLongObject
*tmp
, *new;
2237 assert(PyType_IsSubtype(type
, &PyLong_Type
));
2238 tmp
= (PyLongObject
*)long_new(&PyLong_Type
, args
, kwds
);
2241 assert(PyLong_CheckExact(tmp
));
2245 new = (PyLongObject
*)type
->tp_alloc(type
, n
);
2248 assert(PyLong_Check(new));
2249 new->ob_size
= tmp
->ob_size
;
2250 for (i
= 0; i
< n
; i
++)
2251 new->ob_digit
[i
] = tmp
->ob_digit
[i
];
2253 return (PyObject
*)new;
2256 static char long_doc
[] =
2257 "long(x[, base]) -> integer\n\
2259 Convert a string or number to a long integer, if possible. A floating\n\
2260 point argument will be truncated towards zero (this does not include a\n\
2261 string representation of a floating point number!) When converting a\n\
2262 string, use the optional base. It is an error to supply a base when\n\
2263 converting a non-string.";
2265 static PyNumberMethods long_as_number
= {
2266 (binaryfunc
) long_add
, /*nb_add*/
2267 (binaryfunc
) long_sub
, /*nb_subtract*/
2268 (binaryfunc
) long_mul
, /*nb_multiply*/
2269 (binaryfunc
) long_classic_div
, /*nb_divide*/
2270 (binaryfunc
) long_mod
, /*nb_remainder*/
2271 (binaryfunc
) long_divmod
, /*nb_divmod*/
2272 (ternaryfunc
) long_pow
, /*nb_power*/
2273 (unaryfunc
) long_neg
, /*nb_negative*/
2274 (unaryfunc
) long_pos
, /*tp_positive*/
2275 (unaryfunc
) long_abs
, /*tp_absolute*/
2276 (inquiry
) long_nonzero
, /*tp_nonzero*/
2277 (unaryfunc
) long_invert
, /*nb_invert*/
2278 (binaryfunc
) long_lshift
, /*nb_lshift*/
2279 (binaryfunc
) long_rshift
, /*nb_rshift*/
2280 (binaryfunc
) long_and
, /*nb_and*/
2281 (binaryfunc
) long_xor
, /*nb_xor*/
2282 (binaryfunc
) long_or
, /*nb_or*/
2283 (coercion
) long_coerce
, /*nb_coerce*/
2284 (unaryfunc
) long_int
, /*nb_int*/
2285 (unaryfunc
) long_long
, /*nb_long*/
2286 (unaryfunc
) long_float
, /*nb_float*/
2287 (unaryfunc
) long_oct
, /*nb_oct*/
2288 (unaryfunc
) long_hex
, /*nb_hex*/
2289 0, /* nb_inplace_add */
2290 0, /* nb_inplace_subtract */
2291 0, /* nb_inplace_multiply */
2292 0, /* nb_inplace_divide */
2293 0, /* nb_inplace_remainder */
2294 0, /* nb_inplace_power */
2295 0, /* nb_inplace_lshift */
2296 0, /* nb_inplace_rshift */
2297 0, /* nb_inplace_and */
2298 0, /* nb_inplace_xor */
2299 0, /* nb_inplace_or */
2300 (binaryfunc
)long_div
, /* nb_floor_divide */
2301 long_true_divide
, /* nb_true_divide */
2302 0, /* nb_inplace_floor_divide */
2303 0, /* nb_inplace_true_divide */
2306 PyTypeObject PyLong_Type
= {
2307 PyObject_HEAD_INIT(&PyType_Type
)
2309 "long", /* tp_name */
2310 sizeof(PyLongObject
) - sizeof(digit
), /* tp_basicsize */
2311 sizeof(digit
), /* tp_itemsize */
2312 (destructor
)long_dealloc
, /* tp_dealloc */
2316 (cmpfunc
)long_compare
, /* tp_compare */
2317 (reprfunc
)long_repr
, /* tp_repr */
2318 &long_as_number
, /* tp_as_number */
2319 0, /* tp_as_sequence */
2320 0, /* tp_as_mapping */
2321 (hashfunc
)long_hash
, /* tp_hash */
2323 (reprfunc
)long_str
, /* tp_str */
2324 PyObject_GenericGetAttr
, /* tp_getattro */
2325 0, /* tp_setattro */
2326 0, /* tp_as_buffer */
2327 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_CHECKTYPES
|
2328 Py_TPFLAGS_BASETYPE
, /* tp_flags */
2329 long_doc
, /* tp_doc */
2330 0, /* tp_traverse */
2332 0, /* tp_richcompare */
2333 0, /* tp_weaklistoffset */
2335 0, /* tp_iternext */
2341 0, /* tp_descr_get */
2342 0, /* tp_descr_set */
2343 0, /* tp_dictoffset */
2346 long_new
, /* tp_new */
2347 _PyObject_Del
, /* tp_free */