binary representation of an integer
Nick Craig-Wood
nick at craig-wood.com
Tue Jun 24 06:32:12 EDT 2008
eliben <eliben at gmail.com> wrote:
> 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:
> 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 this...
>>> hex_to_binary = {
... "0" : "0000",
... "1" : "0001",
... "2" : "0010",
... "3" : "0011",
... "4" : "0100",
... "5" : "0101",
... "6" : "0110",
... "7" : "0111",
... "8" : "1000",
... "9" : "1001",
... "a" : "1010",
... "b" : "1011",
... "c" : "1100",
... "d" : "1101",
... "e" : "1110",
... "f" : "1111",
... }
>>> def to_binary(inp):
... out = []
... for hex_digit in ("%x" % inp):
... out.append(hex_to_binary[hex_digit])
... out = "".join(out).lstrip("0")
... if out == "":
... out = "0"
... return out
...
>>> to_binary(0)
'0'
>>> to_binary(10)
'1010'
>>> to_binary(100)
'1100100'
>>> to_binary(1000)
'1111101000'
>>> to_binary(10000000000000000000)
'1000101011000111001000110000010010001001111010000000000000000000'
But don't try this ;-)
>>> to_binary(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in to_binary
KeyError: '-'
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list