binary representation of an integer

eliben eliben at
Tue Jun 24 10:03:58 CEST 2008


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, so
custom solutions have to be developed. One suggested in the ASPN
cookbook is:
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

What do you think?

More information about the Python-list mailing list