Can string formatting be used to convert an integer to its binary form ?
Frederic Rentsch
anthra.norell at vtxmail.ch
Thu Sep 28 14:43:01 EDT 2006
bearophileHUGS at lycos.com wrote:
> Mirco Wahab:
>
>> But where is the %b in Python?
>>
>
> Python doesn't have that. You can convert the number to a hex, and then
> map the hex digitds to binary strings using a dictionary, like this:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528
>
> Bye,
> bearophile
>
>
Good idea, but shorter with ->
http://cheeseshop.python.org/pypi/SE/2.2%20beta
>>> import SE
>>> Int_To_Binary = SE.SE (SE.SE ('0=0000 1=0001 2=0010 3=0011 4=0100
5=0101 6=0110 7=0111 8=1000 9=1001 A=1010 a=1010 B=1011 b=1011 C=1100
c=1100 D=1101 d=1101 E=1110 e=1110 F=1111 f=1111')
>>> Int_To_Binary ('%x' % 1234567890')
'01001001100101100000001011010010'
>>> Int_To_Binary.save ('se_definition_files/int_to_binary.se')
>>> SE.SE ('se_definition_files/int_to_binary.se') ('%X' % 987654321)
'00111010110111100110100010110001'
Frederic
More information about the Python-list
mailing list