binary representation of an integer

Maric Michaud maric at aristote.info
Tue Jun 24 04:33:07 EDT 2008


Le Tuesday 24 June 2008 10:03:58 eliben, vous avez écrit :
> Hello,
>
> I'm interested in converting integers to a binary representation,
> string. I.e. a desired function would produce:
>
> dec2bin(13) => "1101"
>
> The other way is easily done in Python with the int() function.
>
> Perl has a very efficient way to do dec2bin, because its pack/unpack
> have a B format for binary representations, so it's done with:
>
> sub dec2bin {
>     my $str = unpack("B32", pack("N", shift));
>     $str =~ s/^0+(?=\d)//;   # otherwise you'll get leading zeros
>     return $str;
> }
>
> Python's pack/unpack don't have the binary format for some reason,

Yes, but I think the %b format specifier has been added to p3k but will not in 
python 2.x.

> so 
> custom solutions have to be developed. One suggested in the ASPN
> cookbook is:
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/111286
> However, it is very general and thus inefficient.
>
> What would be the quickest way to do this ? I think that for dec2bin
> conversion, using hex() and then looping with a hex->bin lookup table
> would be probably much faster than the general baseconvert from the
> recipe.
>
> What do you think?


Something like that, less typing with octal conversion :)

>>>[8]: oct2bin = 
{'0':'000', '1':'001', '2':'010', '3':'011', '4':'100', '5':'101', '6':'110', '7':'111'}

>>>[9]: ''.join(oct2bin[e] for e in "%o"%35).lstrip('0')
...[9]: '100011'



-- 
_____________

Maric Michaud
_____________

Aristote - www.aristote.info
3 place des tapis
69004 Lyon
Tel: +33 4 26 88 00 97
Mobile: +33 6 32 77 00 21



More information about the Python-list mailing list