views:

13700

answers:

8

How do you express an integer as a binary number with Python literals?

I was easily able to find the answer for hex:

    >>> 0x12AF
    4783
    >>> 0x100
    256

and, octal:

    >>> 01267
    695
    >>> 0100
    64

How do you use literals to express binary in Python?


Summary of Answers

  • Python 2.5 and earlier: can express binary using int('01010101111',2) but not with a literal.
  • Python 2.5 and earlier: there is no way to express binary literals.
  • Python 2.6 beta: You can do like so: 0b1100111 or 0B1100111.
  • Python 2.6 beta: will also allow 0o27 or 0O27 (second character is the letter O) to represent an octal.
  • Python 3.0 beta: Same as 2.6, but will no longer allow the older 027 syntax for octals.
+1  A: 

As far as I can tell Python, up through 2.5, only supports hexadecimal & octal literals. I did find some discussions about adding binary to future versions but nothing definite.

Mark Biek
+1  A: 

I am pretty sure this is one of the things due to change in Python 3.0 with perhaps bin() to go with hex() and oct().

EDIT: lbrandy's answer is correct in all cases.

sparkes
+23  A: 
>>> print int('01010101111',2)
687
>>> print int('11111111',2)
255

Another way.

edit: Apparently the only way. Since the other way doesn't actually work.

lbrandy
+2  A: 

@sparkes

I think I must be misunderstanding something about eval.

>>> eval('010')
8

How does eval know if it's evaluating binary digits?

Mark Biek
In that case it's evaluting octal digits because the first digit is a '0'
Rory
Octal numbers are prefixed by 0 and hex 0x, so>>> eval('0x100') #evaluated in 16 base256
+1  A: 

@mark

It doesn't. Eval doesn't work as stated above. And you've just proven it.

>>> eval("10")
10

There's no way eval could know whether 10 is supposed to mean 2, in binary, or 10 in decimal.

lbrandy
A: 

@sparkes

0 denotes octal, not binary. eval(010), for example, gives 8, not 2. It doesn't work.

>>> print eval('010')
8

That is not the right answer for a binary to decimal conversion. (However it is for an octal to decimal conversion).

lbrandy
+5  A: 

There is no way you can express binary literals (or rather integers as binary): here's a link to language reference on that matter

Bartosz Radaczyński
+40  A: 
Andreas Thomas