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

user1790201 picture user1790201 · Nov 23, 2012 · Viewed 24.5k times · Source

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]

Answer

Jun HU picture Jun HU · Nov 23, 2012
def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]