Integer to Binary string

darrell dgallion1 at yahoo.com
Sat Dec 7 15:27:44 EST 2002


import time, pprint

def bin(i):
     s = ''
     while i:
         s = (i & 1 and '1' or '0') + s
         i >>= 1
     return s or '0'

hMapMask=0xff
hMapMaskBits=8
hMapSize=0x100

def mkHmap(sz):
    d={}
    pat="%0"+str(hMapMaskBits)+"d"
    for x in range(sz):
        d[x]=pat%(long(bin(x)))
    return d

hMap=mkHmap(hMapSize)
#pprint.pprint(hMap)

def toBaseTwo(i):
    bin=[]
    while i:
        v=i & hMapMask
        i >>= hMapMaskBits
        bin.append(hMap[v])
    bin.reverse()
    return "".join(bin)

def test1(testSize=1000):
    res1=[]
    t1=time.time()
    for x in xrange(1):
        for x in xrange(1,testSize):
#            print "x%8s"%toBaseTwo(x)
            res1.append(toBaseTwo(x))
    print time.time()-t1
            
    res2=[]
    t1=time.time()
    for x in xrange(1):
        for x in xrange(1,testSize):
            res2.append(bin(x))
    print time.time()-t1
        
    
    cnt=0
    for a, b in zip(res1, res2):
        cnt+=1
        try:
            assert  long(a) == long(b)
        except:
            print hex(cnt), `a`, `b`
            print hex(cnt), toBaseTwo(cnt), bin(cnt)
            raise
            
test1(testSize=100000)

---output
        0.95485496521
        2.72809791565

--Darrell


Alfred Morgan wrote:

> def bin(i):
>      s = ''
>      while i:
>          s = (i & 1 and '1' or '0') + s
>          i >>= 1
>      return s or '0'
> 
> 
> srijit at yahoo.com wrote:
>> I would like to know the most efficient Pythonic way to convert an
>> integer to a binary string. Any suggestions?
>> Is there any Python function similar to _itoa?
>> 
>> Thanks




More information about the Python-list mailing list