How do you convert a number to binary without inbuilt function in python?

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]

asked Nov 23, 2012 at 3:36

user1790201user1790201

1591 gold badge1 silver badge5 bronze badges

4

def trans(x):
    if x == 0: return [0]
    bit = []
    while x:
        bit.append(x % 2)
        x >>= 1
    return bit[::-1]

answered Nov 23, 2012 at 3:39

Jun HUJun HU

3,0566 gold badges17 silver badges21 bronze badges

0

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

def tobin(x):
    return tobin(x/2) + [x%2] if x > 1 else [x]

answered Nov 23, 2012 at 4:05

How do you convert a number to binary without inbuilt function in python?

Óscar LópezÓscar López

228k35 gold badges304 silver badges377 bronze badges

3

may I propose this:

def tobin(x,s):
    return [(x>>k)&1 for k in range(0,s)]

it is probably the fastest way and it seems pretty clear to me. bin way is too slow when performance matters.

cheers

answered Jun 11, 2013 at 12:28

3

You can first use the format function to get a binary string like your current function. For e.g the following snippet creates a binary string of 8 bits corresponding to integer 58.

>>>u = format(58, "08b")
'00111010'

Now iterate the string to convert each bit to an int to get your desired list of bits encoded as integers.

>>>[int(d) for d in u]
[0, 0, 1, 1, 1, 0, 1, 0]

answered Apr 8, 2016 at 21:08

theOnetheOne

4014 silver badges4 bronze badges

1

You can use numpy package and get very fast solution:

python -m timeit -s "import numpy as np; x=np.array([8], dtype=np.uint8)" "np.unpackbits(x)"
1000000 loops, best of 3: 0.65 usec per loop

python -m timeit "[int(x) for x in list('{0:0b}'.format(8))]"
100000 loops, best of 3: 3.68 usec per loop

unpackbits handles inputs of uint8 type only, but you can still use np.view:

python -m timeit -s "import numpy as np; x=np.array([124567], dtype=np.uint64).view(np.uint8)" "np.unpackbits(x)"
1000000 loops, best of 3: 0.697 usec per loop

answered Jul 21, 2016 at 5:19

bubblebubble

1,56411 silver badges16 bronze badges

This will do it. No sense in rolling your own function if there's a builtin.

def binary(x):
    return [int(i) for i in bin(x)[2:]]

The bin() function converts to a string in binary. Strip of the 0b and you're set.

answered Nov 23, 2012 at 3:41

Dietrich EppDietrich Epp

198k36 gold badges333 silver badges411 bronze badges

9

Here is the code for one that I made for college. Click Here for a youtube video of the code.! https://www.youtube.com/watch?v=SGTZzJ5H-CE

__author__ = 'Derek'
print('Int to binary')
intStr = input('Give me an int: ')
myInt = int(intStr)
binStr = ''
while myInt > 0:
    binStr = str(myInt % 2) + binStr
    myInt //= 2
print('The binary of', intStr, 'is', binStr)
print('\nBinary to int')
binStr = input('Give me a binary string: ')
temp = binStr
newInt = 0
power = 0
while len(temp) > 0:   # While the length of the array if greater than zero keep looping through
    bit = int(temp[-1])   # bit is were you temporally store the converted binary number before adding it to the total
    newInt = newInt + bit * 2 ** power  # newInt is the total,  Each time it loops it adds bit to newInt.
    temp = temp[:-1]  # this moves you to the next item in the string.
    power += 1  # adds one to the power each time.
print("The binary number " + binStr, 'as an integer is', newInt)

answered Oct 19, 2014 at 11:54

How do you convert a number to binary without inbuilt function in python?

Derek MCDerek MC

3662 gold badges4 silver badges24 bronze badges

Padded with length

In most cases you want your binary number to be a specific length. For example you want 1 to be 8 binary digits long [0,0,0,0,0,0,0,1]. I use this myself:

def convert_to_binary(num, length=8):
    binary_string_list = list(format(num, '0{}b'.format(length)))
    return [int(digit) for digit in binary_string_list]

answered Feb 16, 2015 at 14:05

Not really the most efficient but at least it provides a simple conceptual way of understanding it...

1) Floor divide all the numbers by two repeatedly until you reach 1

2) Going in reverse order, create bits of this array of numbers, if it is even, append a 0 if it is odd append a 1.

Here's the literal implementation of that:

def intToBin(n):
    nums = [n]
    while n > 1:
        n = n // 2
        nums.append(n)

    bits = []
    for i in nums:
        bits.append(str(0 if i%2 == 0 else 1))
    bits.reverse()
    print ''.join(bits)

Here's a version that better utilizes memory:

def intToBin(n):
    bits = []

    bits.append(str(0 if n%2 == 0 else 1))
    while n > 1:
        n = n // 2
        bits.append(str(0 if n%2 == 0 else 1))

    bits.reverse()
    return ''.join(bits)

answered Apr 17, 2016 at 18:31

How do you convert a number to binary without inbuilt function in python?

ThinkBonoboThinkBonobo

14.3k8 gold badges58 silver badges80 bronze badges

Not the pythonic way...but still works:

def get_binary_list_from_decimal(integer, bits):
    '''Return a list of 0's and 1's representing a decimal type integer.

    Keyword arguments:
    integer -- decimal type number.
    bits -- number of bits to represent the integer.

    Usage example:
    #Convert 3 to a binary list
    get_binary_list_from_decimal(3, 4)
    #Return will be [0, 0, 1, 1]
    '''
    #Validate bits parameter.
    if 2**bits <= integer:
        raise ValueError("Error: Number of bits is not sufficient to \
                          represent the integer. Increase bits parameter.")

    #Initialise binary list
    binary_list = []
    remainder = integer
    for i in range(bits-1, -1, -1):
        #If current bit value is less than or equal to the remainder of 
        #the integer then bit value is 1.
        if 2**i <= remainder:
            binary_list.append(1)
            #Subtract the current bit value from the integer.
            remainder = remainder - 2**i
        else:
            binary_list.append(0)

    return binary_list

Example of how to use it:

get_binary_list_from_decimal(1, 3)
#Return will be [0, 0, 1]

answered Aug 31, 2016 at 22:29

theQuestionMantheQuestionMan

9732 gold badges12 silver badges27 bronze badges

def nToKBit(n, K=64):
   output = [0]*K

   def loop(n, i):
       if n == 0: 
           return output
       output[-i] = n & 1
       return loop(n >> 1, i+1)

   return loop(n, 1)

answered Aug 21, 2017 at 3:08

Converting decimal to binary is a matter of how you are going to use the % and //

def getbin(num):
    if (num==0):
        k=[0] 
        return k 
    else:
        s = []
        while(num):
            s.append(num%2)
            num=num//2
        return s

answered Oct 15, 2018 at 9:04

How do you convert a number to binary without inbuilt function in python?

1

Just sharing a function that processes an array of ints:

def to_binary_string(x):
    length = len(bin(max(x))[2:])

    for i in x:
        b = bin(i)[2:].zfill(length)

        yield [int(n) for n in b]

Test:

x1 = to_binary_string([1, 2, 3])
x2 = to_binary_string([1, 2, 3, 4])

print(list(x1)) # [[0, 1], [1, 0], [1, 1]]
print(list(x2)) # [[0, 0, 1], [0, 1, 0], [0, 1, 1], [1, 0, 0]]

answered May 3, 2019 at 8:36

RendicahyaRendicahya

4,1057 gold badges35 silver badges56 bronze badges

Convert integer to list of bits with a fixed length :

[int(x) for x in list('{0:0{width}b}'.format(8, width=5))]

answered Aug 22, 2020 at 10:52

florexflorex

8787 silver badges9 bronze badges

# dec2bin.py
# FB - 201012057
import math

def dec2bin(f):
    if f >= 1:
        g = int(math.log(f, 2))
    else:
        g = -1
    h = g + 1
    ig = math.pow(2, g)
    st = ""    
    while f > 0 or ig >= 1: 
        if f < 1:
            if len(st[h:]) >= 10: # 10 fractional digits max
                   break
        if f >= ig:
            st += "1"
            f -= ig
        else:
            st += "0"
        ig /= 2
    st = st[:h] + "." + st[h:]
    return st

# MAIN
while True:
    f = float(raw_input("Enter decimal number >0: "))
    if f <= 0: break
    print "Binary #: ", dec2bin(f)
    print "bin(int(f)): ", bin(int(f)) # for comparison

How do you convert a number to binary without inbuilt function in python?

Chris

118k88 gold badges261 silver badges241 bronze badges

answered Apr 2, 2014 at 8:44

2

How do you convert int to binary in Python?

To convert int to binary in Python, use the bin() method. The bin() is a built-in Python method that converts a decimal to a binary data type. The bin() function accepts a number as an argument and returns its equivalent binary string prefixed with “0b”.

How do you convert a number to binary without 0b in Python?

Python bin() Without '0b' Prefix To skip the prefix, use slicing and start with index 2 on the binary string. For example, to skip the prefix '0b' on the result of x=bin(2)='0b10' , use the slicing operation x[2:] that results in just the binary number '10' without the prefix '0b' .

How do you convert a number to binary manually?

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 find the binary digit of a number in Python?

Convert number into it's binary using bin() function and remove starting two characters '0b' of output binary string because bin function appends '0b' as prefix in output string. Now print length of binary string that will be the count of bits in binary representation of input number.