Python Int to Binary String

Python int to binary string?

Python's string format method can take a format spec.

>>> "{0:b}".format(37)
'100101'

Format spec docs for Python 2

Format spec docs for Python 3

Convert base-2 binary number string to int

You use the built-in int() function, and pass it the base of the input number, i.e. 2 for a binary number:

>>> int('11111111', 2)
255

Here is documentation for Python 2, and for Python 3.

Converting integer to binary in python

>>> '{0:08b}'.format(6)
'00000110'

Just to explain the parts of the formatting string:

  • {} places a variable into a string
  • 0 takes the variable at argument position 0
  • : adds formatting options for this variable (otherwise it would represent decimal 6)
  • 08 formats the number to eight digits zero-padded on the left
  • b converts the number to its binary representation

If you're using a version of Python 3.6 or above, you can also use f-strings:

>>> f'{6:08b}'
'00000110'

Convert to binary and keep leading zeros

Use the format() function:

>>> format(14, '#010b')
'0b00001110'

The format() function simply formats the input following the Format Specification mini language. The # makes the format include the 0b prefix, and the 010 size formats the output to fit in 10 characters width, with 0 padding; 2 characters for the 0b prefix, the other 8 for the binary digits.

This is the most compact and direct option.

If you are putting the result in a larger string, use an formatted string literal (3.6+) or use str.format() and put the second argument for the format() function after the colon of the placeholder {:..}:

>>> value = 14
>>> f'The produced output, in binary, is: {value:#010b}'
'The produced output, in binary, is: 0b00001110'
>>> 'The produced output, in binary, is: {:#010b}'.format(value)
'The produced output, in binary, is: 0b00001110'

As it happens, even for just formatting a single value (so without putting the result in a larger string), using a formatted string literal is faster than using format():

>>> import timeit
>>> timeit.timeit("f_(v, '#010b')", "v = 14; f_ = format") # use a local for performance
0.40298633499332936
>>> timeit.timeit("f'{v:#010b}'", "v = 14")
0.2850222919951193

But I'd use that only if performance in a tight loop matters, as format(...) communicates the intent better.

If you did not want the 0b prefix, simply drop the # and adjust the length of the field:

>>> format(14, '08b')
'00001110'

Converting a number to binary with a variable length

You can nest {} formats in f-strings:

>>> s = 6
>>> l = 7
>>> a = f'{s:0{l}b}'
>>> print(a)
0000110

Converting a number to binary with a fixed length

No you don't.

>>> '{0:07b}'.format(12)
'0001100'

convert a number or string to binary number in python?

The hexadecimal number 0xB15 = 2837 has the binary representation 0b101100010101. So if your input is a hexadecimal number, you need to tell Python to convert the string "B15" which comes out of input() into the hexadecimal number 0xB15, also known as the decimal number 2837, before you can convert it into binary for output.

BASE = 16
a = int(input(), BASE)
print(bin(a)[2:]) # Cut of the first two characters '0b'

Fastest Way to convert a Binary String to Binary Array (Array of 1 and 0)

bytearray appears to be even faster than Andrej's NumPy solution. And bytes can be used for a fast list solution. Times with 1024 bits (only showing the first 5):

f1   2.7 μs  [1 0 1 1 1]
f2 2.0 μs bytearray(b'\x01\x00\x01\x01\x01')
f3 7.6 μs [1, 0, 1, 1, 1]

Code based on Andrej's (Try it online!):

import numpy as np
from timeit import timeit

s = "1011" * 256 # length = 1024


def f1():
return np.frombuffer(s.encode("ascii"), dtype="u1") - 48


table = bytearray.maketrans(b'01', b'\x00\x01')

def f2():
return bytearray(s, "ascii").translate(table)


def f3():
return [*s.encode().translate(table)]


for _ in range(3):
for f in f1, f2, f3:
t = timeit(f, number=1_000)
t = '%5.1f μs ' % (t * 1e3)
print(f.__name__, t, f()[:5])
print()

How to convert string and integer to binary in nodejs?

You should loop through the string and do this on each character: