In order to convert an integer to a binary, I have used this code :
>>> bin[6]
'0b110'
and when to erase the '0b', I use this :
>>> bin[6][2:]
'110'
What can I do if I want to show 6
as 00000110
instead of 110
?
just-Luka
3171 gold badge4 silver badges17 bronze badges
asked May 2, 2012 at 9:31
1
>>> '{0:08b}'.format[6]
'00000110'
Just to explain the parts of the formatting string:
{}
places a variable into a string0
takes the variable at argument position 0:
adds formatting options for this variable [otherwise it would represent decimal6
]08
formats the number to eight digits zero-padded on the leftb
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'
TrebledJ
8,1027 gold badges23 silver badges46 bronze badges
answered May 2, 2012 at 9:32
eumiroeumiro
198k33 gold badges294 silver badges259 bronze badges
5
Just another idea:
>>> bin[6][2:].zfill[8]
'00000110'
Shorter way via string interpolation [Python 3.6+]:
>>> f'{6:08b}'
'00000110'
answered May 2, 2012 at 9:37
mshsayemmshsayem
17.2k11 gold badges61 silver badges67 bronze badges
3
A bit twiddling method...
>>> bin8 = lambda x : ''.join[reversed[ [str[[x >> i] & 1] for i in range[8]] ] ]
>>> bin8[6]
'00000110'
>>> bin8[-3]
'11111101'
marbel82
8871 gold badge18 silver badges38 bronze badges
answered May 2, 2012 at 10:07
sobelsobel
6335 silver badges8 bronze badges
3
Just use the format function
format[6, "08b"]
The general form is
format[, ""]
answered Apr 7, 2016 at 20:16
theOnetheOne
4014 silver badges4 bronze badges
1
eumiro's answer is better, however I'm just posting this for variety:
>>> "%08d" % int[bin[6][2:]]
00000110
answered May 2, 2012 at 9:35
jedwardsjedwards
28.7k3 gold badges61 silver badges90 bronze badges
0
numpy.binary_repr[num, width=None]
has a magic width argument
Relevant examples from the documentation linked above:
>>> np.binary_repr[3, width=4] '0011'
The two’s complement is returned when the input number is negative and width is specified:
>>> np.binary_repr[-3, width=5] '11101'
answered May 1, 2019 at 2:11
Tom HaleTom Hale
35.3k27 gold badges163 silver badges224 bronze badges
.. or if you're not sure it should always be 8 digits, you can pass it as a parameter:
>>> '%0*d' % [8, int[bin[6][2:]]]
'00000110'
answered May 2, 2012 at 9:47
thebjornthebjorn
24.9k9 gold badges86 silver badges131 bronze badges
Going Old School always works
def intoBinary[number]:
binarynumber=""
if [number!=0]:
while [number>=1]:
if [number %2==0]:
binarynumber=binarynumber+"0"
number=number/2
else:
binarynumber=binarynumber+"1"
number=[number-1]/2
else:
binarynumber="0"
return "".join[reversed[binarynumber]]
answered Jun 8, 2018 at 16:40
2
The best way is to specify the format.
format[a, 'b']
returns the binary value of a in string format.
To convert a binary string back to integer, use int[] function.
int['110', 2]
returns integer value of binary string.
answered Apr 27, 2020 at 3:18
PranjalyaPranjalya
682 silver badges7 bronze badges
1
Assuming you want to parse the number of digits used to represent from a variable which is not always constant, a good way will be to use numpy.binary.
could be useful when you apply binary to power sets
import numpy as np
np.binary_repr[6, width=8]
answered Mar 11, 2020 at 13:31
amaama
431 silver badge7 bronze badges
even an easier way
my_num = 6
print[f'{my_num:b}']
answered Sep 11, 2020 at 2:33
Raad AltaieRaad Altaie
7551 gold badge15 silver badges25 bronze badges
['0' * 7 + bin[6][2:]][-8:]
or
right_side = bin[6][2:]
'0' * [ 8 - len[ right_side ]] + right_side
eyllanesc
226k18 gold badges130 silver badges198 bronze badges
answered Sep 5, 2018 at 0:07
1
You can use just:
"{0:b}".format[n]
In my opinion this is the easiest way!
answered Aug 11, 2020 at 17:21
LehaLeha
236 bronze badges
def int_to_bin[num, fill]:
bin_result = ''
def int_to_binary[number]:
nonlocal bin_result
if number > 1:
int_to_binary[number // 2]
bin_result = bin_result + str[number % 2]
int_to_binary[num]
return bin_result.zfill[fill]
answered May 18, 2020 at 9:41
The python package Binary Fractions has a full implementation of binaries as well as binary fractions. You can do your operation as follows:
from binary_fractions import Binary
b = Binary[6] # creates a binary fraction string
b.lfill[8] # fills to length 8
This package has many other methods for manipulating binary strings with full precision.
answered Jul 16, 2021 at 14:49
Simple code with recursion:
def bin[n,number=['']]:
if n==0:
return[number]
else:
number=str[n%2]+number
n=n//2
return bin[n,number]
answered Dec 2, 2021 at 22:11
1