From 53756b1097805e6a7910a1788d6eb7cb190864ba Mon Sep 17 00:00:00 2001 From: Guido van Rossum Date: Fri, 3 Jan 1997 17:14:46 +0000 Subject: [PATCH] Added PyLong_FromUnsignedLong() and PyLong_AsUnsignedLong(). --- Include/longobject.h | 2 ++ Objects/longobject.c | 56 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/Include/longobject.h b/Include/longobject.h index d4bcbad9bf8..88854a618e8 100644 --- a/Include/longobject.h +++ b/Include/longobject.h @@ -44,8 +44,10 @@ extern DL_IMPORT(PyTypeObject) PyLong_Type; #define PyLong_Check(op) ((op)->ob_type == &PyLong_Type) extern PyObject *PyLong_FromLong Py_PROTO((long)); +extern PyObject *PyLong_FromUnsignedLong Py_PROTO((unsigned long)); extern PyObject *PyLong_FromDouble Py_PROTO((double)); extern long PyLong_AsLong Py_PROTO((PyObject *)); +extern unsigned long PyLong_AsUnsignedLong Py_PROTO((PyObject *)); extern double PyLong_AsDouble Py_PROTO((PyObject *)); PyObject *PyLong_FromString Py_PROTO((char *, char **, int)); diff --git a/Objects/longobject.c b/Objects/longobject.c index f98e517b719..36f2a26dc37 100644 --- a/Objects/longobject.c +++ b/Objects/longobject.c @@ -109,6 +109,27 @@ newlongobject(ival) return (object *)v; } +/* Create a new long int object from a C unsigned long int */ + +object * +PyLong_FromUnsignedLong(ival) + unsigned long ival; +{ + /* Assume a C long fits in at most 5 'digits' */ + /* Works on both 32- and 64-bit machines */ + longobject *v = alloclongobject(5); + if (v != NULL) { + unsigned long t = ival; + int i; + for (i = 0; i < 5; i++) { + v->ob_digit[i] = t & MASK; + t >>= SHIFT; + } + v = long_normalize(v); + } + return (object *)v; +} + /* Create a new long int object from a C double */ object * @@ -181,6 +202,41 @@ getlongvalue(vv) return x * sign; } +/* Get a C long int from a long int object. + Returns -1 and sets an error condition if overflow occurs. */ + +unsigned long +PyLong_AsUnsignedLong(vv) + object *vv; +{ + register longobject *v; + unsigned long x, prev; + int i; + + if (vv == NULL || !is_longobject(vv)) { + err_badcall(); + return (unsigned long) -1; + } + v = (longobject *)vv; + i = v->ob_size; + x = 0; + if (i < 0) { + err_setstr(OverflowError, + "can't convert negative value to unsigned long"); + return (unsigned long) -1; + } + while (--i >= 0) { + prev = x; + x = (x << SHIFT) + v->ob_digit[i]; + if ((x >> SHIFT) != prev) { + err_setstr(OverflowError, + "long int too long to convert"); + return (unsigned long) -1; + } + } + return x; +} + /* Get a C double from a long int object. No overflow check. */ double