Login | Register For Free | Help
Search for: (Advanced)

Mailing List Archive: Python: Python

binary representation of an integer

 

 

Python python RSS feed   Index | Next | Previous | View Threaded


eliben at gmail

Jun 24, 2008, 1:03 AM

Post #1 of 8 (2681 views)
Permalink
binary representation of an integer

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, 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?
--
http://mail.python.org/mailman/listinfo/python-list


maric at aristote

Jun 24, 2008, 1:33 AM

Post #2 of 8 (2655 views)
Permalink
Re: binary representation of an integer [In reply to]

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
--
http://mail.python.org/mailman/listinfo/python-list


dickinsm at gmail

Jun 24, 2008, 1:38 AM

Post #3 of 8 (2654 views)
Permalink
Re: binary representation of an integer [In reply to]

On Jun 24, 9:03 am, eliben <eli...@gmail.com> wrote:
> 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.

I suspect you're right, but it would be easy to find out: just
code up the hex->bin method and use the timeit module to do some
timings. Don't forget to strip the trailing 'L' from hex(n) if n
is a long.

If you're prepared to wait for Python 2.6, or work with the beta
version, then the conversion is already there:

Macintosh-3:trunk dickinsm$ ./python.exe
Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bin(13)
'0b1101'

Interestingly, unlike hex and oct, bin doesn't add a trailing
'L' for longs:

>>> bin(13L)
'0b1101'

I wonder whether this is a bug...

Mark
--
http://mail.python.org/mailman/listinfo/python-list


nick at craig-wood

Jun 24, 2008, 3:32 AM

Post #4 of 8 (2654 views)
Permalink
Re: binary representation of an integer [In reply to]

eliben <eliben [at] gmail> 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> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


cokofreedom at gmail

Jun 24, 2008, 4:57 AM

Post #5 of 8 (2657 views)
Permalink
Re: binary representation of an integer [In reply to]

On Jun 24, 10:38 am, Mark Dickinson <dicki...@gmail.com> wrote:
> On Jun 24, 9:03 am, eliben <eli...@gmail.com> wrote:
>
> > 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.
>
> I suspect you're right, but it would be easy to find out: just
> code up the hex->bin method and use the timeit module to do some
> timings. Don't forget to strip the trailing 'L' from hex(n) if n
> is a long.
>
> If you're prepared to wait for Python 2.6, or work with the beta
> version, then the conversion is already there:
>
> Macintosh-3:trunk dickinsm$ ./python.exe
> Python 2.6b1+ (trunk:64489, Jun 23 2008, 21:10:40)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.>>> bin(13)
>
> '0b1101'
>
> Interestingly, unlike hex and oct, bin doesn't add a trailing
> 'L' for longs:
>
> >>> bin(13L)
>
> '0b1101'
>
> I wonder whether this is a bug...
>
> Mark

Strange in 2.6, but I know at least in 3.0 that all integers are C
Long's now, so the L is no longer required.
--
http://mail.python.org/mailman/listinfo/python-list


cokofreedom at gmail

Jun 24, 2008, 5:01 AM

Post #6 of 8 (2666 views)
Permalink
Re: binary representation of an integer [In reply to]

And:

# return as a string
def itob_string(integer, count = 8):
return "".join(str((integer >> i) & 1) for i in range(count - 1,
-1, -1))

# return as an iterator (i.e [0, 0, 0, 0, 1, 0, 1, 0])
def itob_list(integer, count = 8):
return [.(integer >> i) & 1 for i in range(count - 1, -1, -1)]

# return as a generator
def itob_generator(integer, count = 8):
return ((integer >> i) & 1 for i in range(count - 1, -1, -1))
--
http://mail.python.org/mailman/listinfo/python-list


bearophileHUGS at lycos

Jun 24, 2008, 5:53 AM

Post #7 of 8 (2663 views)
Permalink
Re: binary representation of an integer [In reply to]

eliben:
> 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.

Try mine, it may be fast enough for your purposes:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440528

Bye,
bearophile
--
http://mail.python.org/mailman/listinfo/python-list


tjreedy at udel

Jun 24, 2008, 12:06 PM

Post #8 of 8 (2651 views)
Permalink
Re: binary representation of an integer [In reply to]

cokofreedom [at] gmail wrote:
> On Jun 24, 10:38 am, Mark Dickinson <dicki...@gmail.com> wrote:

>> Interestingly, unlike hex and oct, bin doesn't add a trailing
>> 'L' for longs:
>>
>>>>> bin(13L)
>> '0b1101'
>>
>> I wonder whether this is a bug...


> Strange in 2.6, but I know at least in 3.0 that all integers are C
> Long's now, so the L is no longer required.

In current 2.x, the trailing L is no longer required for long integer
input; the lexer decides whether to make an int or long. Similarly,
ints are automatically converted to longs as needed instead of raising
overflow errors (as once happended). The trailing L on output would
have been removed already except for backward compatibility. But there
was no back-compatibility requirement for 0bxxxx strings.

In 3.0, all integers are class 'int'. The internal representation as
fixed or extended precision is entirely an internal implementation matter.

--
http://mail.python.org/mailman/listinfo/python-list

Python python RSS feed   Index | Next | Previous | View Threaded
 
 


Interested in having your list archived? Contact Gossamer Threads
 
  Web Applications & Managed Hosting Powered by Gossamer Threads Inc.