# [Tutor] Function for converting ints from base10 to base2?

David Perlman dperlman at wisc.edu
Wed Feb 21 14:00:33 CET 2007

```d'oh, I fell for the "reply-all" trick.  :)

Here's the code in question:

Apparently there are built in functions hex() and oct() to generate
hexadecimal and octal digit strings of numbers, but there's no
corresponding bin().  Kind of a bizarre oversight, if you ask me.

Searching on the internet, I found this:

def bin(integer, returnType=str):
bin =
{'0':'000','1':'001','2':'010','3':'011','4':'100','5':'101','6':'110','
7':'111'}
if returnType == int:
return int(''.join([bin[i] for i in oct(integer)]))
elif returnType == long:
return long(''.join([bin[i] for i in oct(integer)]),10)
else:
return (''.join([bin[i] for i in oct(integer)])).lstrip("0")

Just define this in the program you are writing and use bin as you
would use oct or hex, making sure to specify int or long as the return
type if you don't want a str.

On Feb 21, 2007, at 1:18 AM, Dick Moores wrote:

> Well, I can't compare mine with yours (where is it?), but using the
> template in timeit.py:
>
> template = """
> def inner(_it, _timer):
>     from decToBin import computeBin
>     _t0 = _timer()
>     for _i in _it:
>         computeBin(12345678901234567890)
>     _t1 = _timer()
>     return _t1 - _t0
> """
> I get these results:
>
> for computeBin(12345678901234567890)
> 1000 loops, best of 3: 448 usec per loop
>
> for computeBin(1234567890)
> 10000 loops, best of 3: 59.7 usec per loop
>
> for computeBin(12345)
> 10000 loops, best of 3: 35.2 usec per loop
>
> Dick Moores
>
> At 09:04 PM 2/20/2007, David Perlman wrote:
>> I suspect the function I sent out earlier, using octal conversion and
>> a lookup table, will be faster.  But it would be very interesting to
>> see some simple benchmarks.
>>
>> On Feb 20, 2007, at 10:47 PM, Dick Moores wrote:
>>
>> > I was surprised to be unable to find a function in Python for
>> > converting ints from base10 to base2. Is there one?
>> >
>> > I wrote one, but have I reinvented the wheel again? (Even if I
>> have,
>> > it was an interesting exercise for me.)
>> >
>> > I know some of you CS people won't like what I do with negative
>> ints,
>> > but I wanted it this way. On other points than that, I'd appreciate
>> > criticism/suggestions.
>> >
>> > ===========================================================
>> > def computeBin(n):
>> >      """converts base10 integer n to base2 b as string"""
>> >      from math import log, floor
>> >      sign = ''
>> >      if n == 0:
>> >          b = '0'
>> >      else:
>> >          if n < 0:
>> >              sign = "-"
>> >              n = -n
>> >          e = int(floor(log(n,2)))
>> >          b = '1'
>> >
>> >          for x in range(e):
>> >              r = n % 2**e
>> >              if r >= 2**(e-1):
>> >                  b += '1'
>> >              else:
>> >                  b += '0'
>> >              e -= 1
>> >      return sign + b
>> >
>> > def printResult(n,b):
>> >      print "%d is %s" % (n, b)
>> >
>> > def confirmResult(n,b):
>> >      print "Confirming using int():"
>> >      print "int(%s,2) is %s" % (b, int(b,2))
>> >
>> > if __name__ == '__main__':
>> >      n = 1234567890
>> >      b = computeBin(n)
>> >      printResult(n,b)
>> >      confirmResult(n,b)
>> > ==============================================
>> >
>> > Dick Moores
>> >
>>
>> --
>> -dave----------------------------------------------------------------
>> After all, it is not *that* inexpressible.
>> -H.H. The Dalai Lama
>
>

--
-dave----------------------------------------------------------------
After all, it is not *that* inexpressible.
-H.H. The Dalai Lama

```