Python int to binary string?

后端 未结 30 2036
执念已碎
执念已碎 2020-11-22 05:34

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I

30条回答
  •  野性不改
    2020-11-22 05:57

    one-liner with lambda:

    >>> binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
    

    test:

    >>> binary(5)
    '101'
    



    EDIT:

    but then :(

    t1 = time()
    for i in range(1000000):
         binary(i)
    t2 = time()
    print(t2 - t1)
    # 6.57236599922
    

    in compare to

    t1 = time()
    for i in range(1000000):
        '{0:b}'.format(i)
    t2 = time()
    print(t2 - t1)
    # 0.68017411232
    

提交回复
热议问题