integer to binary...

Schüle Daniel uval at rz.uni-karlsruhe.de
Thu Jun 1 15:28:58 EDT 2006


nicolasg at gmail.com schrieb:
> does anyone know a module or something to convert numbers like integer
> to binary format ?

unfortunately there is no builtin function for this

 >>> int("111",2)
7
 >>> str(7)
'7'
 >>> str(7,2)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: str() takes at most 1 argument (2 given)
 >>>

int, str are not symmetrical
I hope this will change in future

<rebel on>

you can use Ruby's 7.to_s(2) for this
irb(main):001:0> 7.to_s(2)
=> "111"
irb(main):002:0> 7.to_s(3)
=> "21"
irb(main):003:0>

</rebel on>

> for example I want to convert number 7 to 0111 so I can make some
> bitwise operations...

you can use bitwise operations on int's anyway

7 & 3 == 3
(1 << 20) | (1 << 10) == 2**20+2**10

and so on



More information about the Python-list mailing list