bitsize?

Will Ware wware at world.std.com
Thu Mar 16 17:43:01 EST 2000


David C. Ullrich (ullrich at math.okstate.edu) wrote:
>     Some comments of mine in the past have been misinterpreted
> as requests for changes when they really were not that at all.
> Here otoh I have a request: It would be nice if there was a
> builtin "bitsize" function returning the number of bits in a
> long value. (Ie ceil(log_2(n)), more or less).

This may never make it into the core distribution, but it wouldn't
be too hard to implement this in a private build. Look at
Objects/longobject.c and Include/longobject.h. In the latter you
see:

struct _longobject {
        PyObject_HEAD
        int ob_size;
        digit ob_digit[1];
};

You can find out how big a PyObject_HEAD and an int are, and a
"digit" is just an unsigned short. The ob_digit[] array grows to
handle the required size of the long. So you want a function that
does something a bit like this:

PyObject *long_bitsize(PyObject *self, PyObject *args)
{
	PyLongObject *lobj;
	int size;
	if (!PyArg_ParseTuple(args, "O", &lobj))
		return NULL;
	/* Do something with PyLong_Check(lobj) */
	size = SOME_CONSTANT + lobj->ob_size * sizeof(unsigned short);
	return Py_BuildValue("i", 8 * size);
}

Then you want to make this an attribute of the longobject definition.
To see how, look at Objects/xxobject.c, particularly where you see
xx_methods and xx_getattr. Your long_bitsize function will be
analogous to the xx_demo function.
-- 
 - - - - - - - - - - - - - - - - - - - - - - - -
Resistance is futile. Capacitance is efficacious.
Will Ware	email:    wware @ world.std.com



More information about the Python-list mailing list