Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting integer to binary in python

People also ask

How do you convert a number to binary without inbuilt function in Python?

Traditional method to Convert Python int to Binary (without any function): Firstly, divide the number by 2 and add the remainder to a list. Then continue step 1 till the number is greater than 0. After this, reverse the list.

How do you convert a number to binary without 0b in Python?

Python bin() Without '0b' Prefix To skip the prefix, use slicing and start with index 2 on the binary string. For example, to skip the prefix '0b' on the result of x=bin(2)='0b10' , use the slicing operation x[2:] that results in just the binary number '10' without the prefix '0b' .


>>> '{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'

Just another idea:

>>> bin(6)[2:].zfill(8)
'00000110'

Shorter way via string interpolation (Python 3.6+):

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

A bit twiddling method...

>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'

Just use the format function

format(6, "08b")

The general form is

format(<the_integer>, "<0><width_of_string><format_specifier>")

eumiro's answer is better, however I'm just posting this for variety:

>>> "%08d" % int(bin(6)[2:])
00000110