Using Python to convert integer to binary

24,794

Solution 1

Are you aware of the builtin bin function?

>>> bin(100)
'0b1100100'
>>> bin(1)
'0b1'
>>> bin(0)
'0b0'

Solution 2

You are on the right track, you just need to save the digits in a variable somewhere instead of just printing them to the screen:

num_str = input("Please give me a integer: ")

num_int = int(num_str)

num_bin_reversed = ''

while num_int > 0:

    if num_int % 2 == 0:
        num_int = int(num_int / 2)
        num_remainder = 1
        print("The remainder is:", 0)
        num_bin_reversed += '0'

    elif num_int % 2 == 1:
        num_int = int(num_int / 2)
        num_remainder = 1
        print("The remainder is:", 1)
        num_bin_reversed += '1'

num_bin = num_bin_reversed[::-1]
if int(num_str) > 0:
  assert '0b' + num_bin == bin(int(num_str))

Now, try to fix it by making it work with negative numbers and 0 too!

Solution 3

#First off yes there is an easier way to convert i.e bin(int) but where is the fun in that


"""First we ask the user to input a number. In Python 3+ raw input is gone
so the variable integer_number will actually be a string"""

integer_number = input('Please input an integer') #get integer whole number off user

"""We could use int(input('Please input an integer')) but we don't want to overload
anyones brains so we show casting instead"""

'''Next we convert the string to an integer value (cast). Unless the user enters text
then the program will crash. You need to put your own error detection in'''

integer_number = int(integer_number)

"""initialise a variable name result and assign it nothing.
This so we can add to it later. You can't add things to a place that doesn't exist"""

result = ''  

'''since we are creating an 8bit binary maximum possible number of 255
we set the for loop to 8 (dont forget that x starts at 0'''
for x in range(8):
    #The variable in the for loop will increase by 1 each time
    #Next we get the modulos of the integer_number and assign it to the variable r
    r = integer_number % 2 

    #then we divide integer number by two and put the value back in integer_value
    #we use // instead of / for int division els it will be converted to a float point  variable
    integer_number = integer_number//2

    #Here we append the string value of r which is an integer to result
    result += str(r)


    #This then loops back to the for loop whilst x<8

#then we assign the reverse of result using [::-1] to result
result = result[::-1]

#print out the result
print(result)

Solution 4

You can store the remainders as digits in a string. Here is one possible function to convert from decimal to binary:

def dec2bin(d_num):
    assert d_num >= 0, "cannot convert negative number to binary"
    if d_num == 0:
        return '0'
    b_num = ""
    while d_num > 0:
        b_num = str(d_num%2) + b_num
        d_num = d_num//2
    return b_num
Share:
24,794
A Phototactic Coder
Author by

A Phototactic Coder

Updated on August 03, 2020

Comments

  • A Phototactic Coder
    A Phototactic Coder almost 4 years

    I'm trying to convert integer to binary. This is my work. I don't know how the make a list to show the binary.

    num_str = input("Please give me a integer: ")
    
    num_int = int(num_str)
    
    while num_int > 0:
    
        if num_int % 2 == 0:
            num_int = int(num_int / 2)
            num_remainder = 1
            print("The remainder is:", 0)
            continue
    
        elif num_int % 2 == 1:
            num_int = int(num_int / 2)
            num_remainder = 1
            print("The remainder is:", 1)
            continue
    

    How to make the remainder together?

  • A Phototactic Coder
    A Phototactic Coder over 11 years
    This is very helpful! Thanks! I am working on the negative number and 0.
  • Machavity
    Machavity over 10 years
    You might want to elaborate on your answer some more. People tend to ask questions to learn and not just get an answer.
  • Mixstah
    Mixstah over 10 years
    Machavity this is the exact same answer I posted above with detailed comments. This is just the code without comments as it states at the top.