This function receives as a parameter an integer and should return a list representing the same value expressed in binary as a list of bits, where the first element in the list is the most significant (leftmost) bit.
My function currently outputs '1011'
for the number 11, I need [1,0,1,1]
instead.
For example,
>>> convert_to_binary(11)
[1,0,1,1]
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.
To convert integer to binary, start with the integer in question and divide it by 2 keeping notice of the quotient and the remainder. Continue dividing the quotient by 2 until you get a quotient of zero. Then just write out the remainders in the reverse order.
In Python, you can simply use the bin() function to convert from a decimal value to its corresponding binary value. And similarly, the int() function to convert a binary to its decimal value. The int() function takes as second argument the base of the number to be converted, which is 2 in case of binary numbers.
The bin() function returns the binary version of a specified integer. The result will always start with the prefix 0b .
Just for fun - the solution as a recursive one-liner:
def tobin(x):
return tobin(x/2) + [x%2] if x > 1 else [x]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With