Does Python allow access to some of the implementation details?

Bengt Richter bokr at oz.net
Sat Jan 7 15:43:39 EST 2006


On Sat, 07 Jan 2006 14:05:18 +0100, Claudio Grondi <claudio.grondi at freenet.de> wrote:
[...]
>What I am also looking for is a conversion to base 256 (i.e where the 
>full byte is used and the string and the integer have the same actual 
>content if on appropriate endian machine), which would make the bit 
>extraction comparable easy and effective as the i.__hex__() based method.
>Using digits() instead of the code you have provided speeds the whole 
>thing up two times (see attached code for details), but still is 
>i.__hex__() the best way to go and could be improved probably only by 
>direct conversion to base 256 or even higher base as e.g. 2**16 or 2**32.
>
(see Paul Rubin's post first).
BTW, I'd bet that '%x'.__mod__(i) will save you time over i.__hex__() by the time
you finish fiddling with 0x and L, even if you don't use the rest.

The question looming is, "What are you intending to do with your new representations
of twos complement integers?"

BTW2, an easy way to play with integers chopped into little-endian bit field sequences is
a generator, e.g., (note that last field is sign bits, either all zeroes or all ones, so
you can unambiguously reconstruct a signed integer from this variable width representation).
(not very tested, and BTW as you see I hacked in using int when possible for return values)

 >>> def bitsof(n, width=8):
 ...     m = (2**(width-1)-1)*2+1 # allow 2**width-1 == sys.maxint as int
 ...     if type(m) is long:
 ...         yield n&m
 ...         while n>0 or n<-1:
 ...             n>>=width
 ...             yield n&m
 ...     else:
 ...         yield int(n&m)
 ...         while n>0 or n<-1:
 ...             n>>=width
 ...             yield int(n&m)
 ...
 >>> list(bitsof(11,1))
 [1, 1, 0, 1, 0]
 >>> list(bitsof(5,1))
 [1, 0, 1, 0]
 >>> list(bitsof(-5,1))
 [1, 1, 0, 1]
 >>> hex(3**100)
 '0x5A4653CA673768565B41F775D6947D55CF3813D1L'
 >>> ''.join(map('%02X'.__mod__, bitsof(3**100, 8))[::-1])
 '005A4653CA673768565B41F775D6947D55CF3813D1'
 >>> ''.join(map('%02X'.__mod__, bitsof(-3**100, 8))[::-1])
 'FFA5B9AC3598C897A9A4BE088A296B82AA30C7EC2F'
 >>> hex(-3**100)
 '-0x5A4653CA673768565B41F775D6947D55CF3813D1L'

<gentle rant>
(I leave it to your judgement as to how useful our current hex() representation
of negative numebers is ;-)
</gentle rant>

Regards,
Bengt Richter



More information about the Python-list mailing list