[Python-Dev] Access to bits for a PyLongObject

Eric V. Smith eric+python-dev at trueblade.com
Tue Mar 6 02:57:38 CET 2007

I'm working on PEP 3101, Advanced String Formatting.  About the only 
built-in numeric formatting I have left to do is for converting a 
PyLongOjbect to binary.

I need to know how to access the bits in a PyLong.  After reading 
longobject.c, I can figure it out.  But I'm looking for something that 
might be preferable to me poking around directly in ob_size and ob_digit[].

I'm looking for something along the lines of:
for (i = 0; i < _PyLong_NumBits(v); i++) {
     // get i-th bit of v

I don't care if it's increasing or decreasing bits, I can handle either. 
  I realize the actual code will likely involve the 2 nested loops, but 
logically this is what I need.

I can certainly do this myself, by looping over ob_digit and then over 
each bit.  But there's a comment in longintrepr.h that says the 
internals are published only for marshal.c.  Should I go ahead and 
include longintrepr.h and loop over ob_digit myself, or is there some 
other method?  I really don't want to use _PyLong_AsByteArray, since I 
don't want to do the copy.

If I'm missing some PyLongObject API, please let me know.

By the way, while doing this I noticed a bug in stringobject.c and 
unicodeobject.c, relating to a missing check for 'G' precision.  I'm not 
sure if it could be a buffer overflow or not, without spending some more 
time analyzing at it.  But it seems like the potential is certainly 
there.  The bug is at http://python.org/sf/1673757 and a patch at 

(I'll save my comments on how "approachable" python-dev is after I have 
this question answered!)

Thanks for your time.

More information about the Python-Dev mailing list