Bitwise OR?

Adam DePrince adam.deprince at gmail.com
Fri Mar 24 15:52:19 CET 2006


On Fri, 2006-03-24 at 12:55 +0100, Clemens Hepper wrote:
> Hello,
> 
> I've written a little (optimized) method to get a bit-string:
> 
> def bitstringneg(number, digits=32):
>   """optimized for negative numbers"""
>   result = ""
>   for a in xrange(digits):
>     if number & 1:
>       result += '1'
>     else:
>       result += '0'
>     number >>= 1
>   return result
> 
> def bitstringpos(number):
>   """optimized for positive numbers"""
>   result = ""
>   while number:
>     if number & 1:
>       result += '1'
>     else:
>       result += '0'
>     number >>= 1
>   return result
> 
> def bitstring(number, digits=32):
>   """lsb------>msb"""
>   result = ""
>   if number < 0:
>     return bitstringneg(number, digits)
>   else:
>     return bitstringpos(number)
> 
> BTW: Is there something like a sizeof() method for int numbers?

import struct
help( strict.calcsize ) 

Why one bit at a time?


If I rewrite your functions as: 

_octets = {"0":"000", "1":"001","2":"010",
            "3":"011", "4":"100","5":"101",
            "6":"110", "7":"111", "-":"" }

_sign = {True:'-',False:''}

def bitstring1( number ):
    return _sign[number<0] + ''.join( [_nibbles[d] for d in
hex( number )] ).lstrip( '0' )

    
_nibbles = {"0":"0000", "1":"0001", "2":"0010", "3":"0011",
            "4":"0100", "5":"0101", "6":"0110", "7":"0111",
            "8":"1000", "9":"1001", "a":"1010", "b":"1011",
            "c":"1100", "d":"1101", "e":"1110", "f":"1111",
            "-":"", "x":""}


def bitstring2( number ):
    return _sign[number<0] + ''.join( [_nibbles[d] for d in
hex( number )] ).lstrip( '0' )

Now I know, my negative number sematincs are different than yours, I'll
leave fixing that as an exercise to you.


python2.4 -mtimeit -s 'from test_a import bitstring'
'bitstring(343890242);bitstring(-343890242)'
10000 loops, best of 3: 27.1 usec per loop

python2.4 -mtimeit -s 'from test_b import bitstring1'
'bitstring1(343890242);bitstring1(-343890242)'
100000 loops, best of 3: 10.9 usec per loop

python2.4 -mtimeit -s 'from test_b import bitstring2'
'bitstring2(343890242);bitstring2(-343890242)'
100000 loops, best of 3: 11.2 usec per loop


And if I use a map, well, its not a statistically significant
difference. 

def bitstring_nibblemap( number ):
    return _sign[number<0] + ''.join( map( _nibbles.get,
hex( number ))).lstrip( '0' )

python2.4 -mtimeit -s 'from test_b import bitstring_nibblemap'
'bitstring_nibblemap(343890242);bitstring_nibblemap(-343890242)'
100000 loops, best of 3: 10.7 usec per loop


Cheers - Adam




More information about the Python-list mailing list