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?
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?
>>> '{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 decimal 6)08 formats the number to eight digits zero-padded on the leftb converts the number to its binary representationIf you're using a version of Python 3.6 or above, you can also use f-strings:
>>> f'{6:08b}'
'00000110'
0 means the 0th argument to format. After the colon is the formatting, the second 0 means zero fill to 8 spaces and b for binaryformat() function: format(6, '08b'); the function takes a value (what the {..} slot applies to) and a formatting specification (whatever you would put after the : in the formatting string).Just another idea:
>>> bin(6)[2:].zfill(8)
'00000110'
Shorter way via string interpolation (Python 3.6+):
>>> f'{6:08b}'
'00000110'
bin(-6)[2:].zfill(8) reads as '0000b110'Just use the format function
format(6, "08b")
The general form is
format(<the_integer>, "<0><width_of_string><format_specifier>")
1000000 loops, best of 3: 556 ns per loopA bit twiddling method...
>>> bin8 = lambda x : ''.join(reversed( [str((x >> i) & 1) for i in range(8)] ) )
>>> bin8(6)
'00000110'
>>> bin8(-3)
'11111101'
x to the right and ANDs it with 1, effectively extracting one bit (0 or 1) at a time.reversed could be removed by using range(7,-1,-1); albeit more ‘pure’, but perhaps less readable/intuitive.numpy.binary_repr(num, width=None) has a magic width argumentRelevant 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'
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.
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))
number=number/2 gives float, so number=number//2 seams better, also I would replace number=number//2 with number//=2 and b=b+"0" with b+="0"number=7, your function returns "111" instead of "0111", this is unexpected.('0' * 7 + bin(6)[2:])[-8:]
or
right_side = bin(6)[2:]
'0' * ( 8 - len( right_side )) + right_side
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)
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.