Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an integer to binary without using the built-in bin function

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]
like image 863
user1790201 Avatar asked Nov 23 '12 03:11

user1790201


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 int to binary?

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.

How do you convert a number to binary in Python?

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.

What is the use of the bin () function?

The bin() function returns the binary version of a specified integer. The result will always start with the prefix 0b .


1 Answers

Just for fun - the solution as a recursive one-liner:

def tobin(x):
    return tobin(x/2) + [x%2] if x > 1 else [x]
like image 155
Óscar López Avatar answered Oct 23 '22 01:10

Óscar López