415

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

I was easily able to find the answer for hex:

>>> 0x12AF4783>>> 0x100256

and octal:

>>> 01267695>>> 010064

How do you use literals to express binary in Python?


Summary of Answers

  • Python 2.5 and earlier: can express binary usingint('01010101111',2) but not with a literal.
  • Python 2.5 and earlier: there isno way to express binary literals.
  • Python 2.6 beta: You can do like so:0b1100111 or0B1100111.
  • Python 2.6 beta: will also allow0o27 or0O27 (second character is the letter O) to represent an octal.
  • Python 3.0 beta: Same as 2.6, but will no longer allow the older027 syntax for octals.
Dimitris Fasarakis Hilliard's user avatar
Dimitris Fasarakis Hilliard
162k35 gold badges282 silver badges265 bronze badges
askedAug 4, 2008 at 18:20
Justin Standard's user avatar
0

8 Answers8

370

For reference—future Python possibilities:
Starting with Python 2.6 you can express binary literals using the prefix0b or0B:

>>> 0b10111147

You can also use the newbin function to get the binary representation of a number:

>>> bin(173)'0b10101101'

Development version of the documentation:What's New in Python 2.6

answeredAug 16, 2008 at 12:35
Andreas Thomas's user avatar
Sign up to request clarification or add additional context in comments.

Comments

88
>>> print int('01010101111',2)687>>> print int('11111111',2)255

Another way.

dave4420's user avatar
dave4420
47.2k6 gold badges121 silver badges153 bronze badges
answeredAug 4, 2008 at 18:34
Louis Brandy's user avatar

1 Comment

This is interesting for when you have strings, but if working with pure numbers, you add unnecessary computations to the code.
41

How do you express binary literals in Python?

They're not "binary" literals, but rather, "integer literals". You can express integer literals with a binary format with a0 followed by aB orb followed by a series of zeros and ones, for example:

>>> 0b0010101010170>>> 0B01010121

From the Python 3docs, these are the ways of providing integer literals in Python:

Integer literals are described by the following lexical definitions:

integer      ::=  decinteger | bininteger | octinteger | hexintegerdecinteger   ::=  nonzerodigit (["_"] digit)* | "0"+ (["_"] "0")*bininteger   ::=  "0" ("b" | "B") (["_"] bindigit)+octinteger   ::=  "0" ("o" | "O") (["_"] octdigit)+hexinteger   ::=  "0" ("x" | "X") (["_"] hexdigit)+nonzerodigit ::=  "1"..."9"digit        ::=  "0"..."9"bindigit     ::=  "0" | "1"octdigit     ::=  "0"..."7"hexdigit     ::=  digit | "a"..."f" | "A"..."F"

There is no limit for the length of integer literals apart from what can be stored in available memory.

Note that leading zeros in a non-zero decimal number are not allowed. This is for disambiguation with C-style octal literals, which Python used before version 3.0.

Some examples of integer literals:

7     2147483647                        0o177    0b1001101113     79228162514264337593543950336     0o377    0xdeadbeef      100_000_000_000                   0b_1110_0101

Changed in version 3.6: Underscores are now allowed for grouping purposes in literals.

Other ways of expressing binary:

You can have the zeros and ones in a string object which can be manipulated (although you should probably just do bitwise operations on the integer in most cases) - just pass int the string of zeros and ones and the base you are converting from (2):

>>> int('010101', 2)21

You can optionally have the0b or0B prefix:

>>> int('0b0010101010', 2)170

If you pass it0 as the base, it will assume base 10 if the string doesn't specify with a prefix:

>>> int('10101', 0)10101>>> int('0b10101', 0)21

Converting from int back to human readable binary:

You can pass an integer to bin to see the string representation of a binary literal:

>>> bin(21)'0b10101'

And you can combinebin andint to go back and forth:

>>> bin(int('010101', 2))'0b10101'

You can use a format specification as well, if you want to have minimum width with preceding zeros:

>>> format(int('010101', 2), '{fill}{width}b'.format(width=10, fill=0))'0000010101'>>> format(int('010101', 2), '010b')'0000010101'
answeredMay 14, 2016 at 11:58
Aaron Hall's user avatar

1 Comment

int(hex(1234), 16) = 1234 :D
3

0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:

>>> int('010101', 0)4161

If you don't start with a 0, then python assumes the number is base 10.

>>> int('10101', 0)10101
answeredJun 21, 2016 at 22:48
Mehmet Ugurbil's user avatar

Comments

3

I've tried this in Python 3.6.9

Convert Binary to Decimal

>>> 0b10111147>>> int('101111',2)47

Convert Decimal to binary

>>> bin(47)'0b101111'

Place a 0 as the second parameter python assumes it as decimal.

>>> int('101111',0)101111
answeredNov 29, 2020 at 4:40
Ranjeet R Patil's user avatar

Comments

1

Another good method to get an integer representation from binary is to use eval()

Like so:

def getInt(binNum = 0):    return eval(eval('0b' + str(n)))

I guess this is a way to do it too.I hope this is a satisfactory answer :D

answeredAug 7, 2020 at 7:45
Novus Edge's user avatar

1 Comment

Nope, not a good method at all. You shouldnever useeval().
-1

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.

answeredAug 4, 2008 at 18:26
Mark Biek's user avatar

Comments

-3

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.

Peter Mortensen's user avatar
Peter Mortensen
31.4k22 gold badges110 silver badges134 bronze badges
answeredAug 4, 2008 at 18:27
sparkes's user avatar

Comments

Protected question. To answer this question, you need to have at least 10 reputation on this site (not counting theassociation bonus). The reputation requirement helps protect this question from spam and non-answer activity.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.