6

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?

Martijn Pieters's user avatar
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
askedJan 30, 2013 at 3:49
A Phototactic Coder's user avatar
1
  • num_remainder should be a string, then you concate the1 or0 to it.CommentedJan 30, 2013 at 3:53

8 Answers8

17

Are you aware of the builtinbin function?

>>> bin(100)'0b1100100'>>> bin(1)'0b1'>>> bin(0)'0b0'
answeredJan 30, 2013 at 3:52
mgilson's user avatar
Sign up to request clarification or add additional context in comments.

Comments

4

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!

answeredJan 30, 2013 at 4:04
wim's user avatar

1 Comment

This is very helpful! Thanks! I am working on the negative number and 0.
1
#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 goneso 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 overloadanyones brains so we show casting instead"""'''Next we convert the string to an integer value (cast). Unless the user enters textthen 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 255we 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 resultresult = result[::-1]#print out the resultprint(result)
answeredNov 15, 2013 at 22:57
Mixstah's user avatar

Comments

1

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
nikpod's user avatar
nikpod
1,27814 silver badges22 bronze badges
answeredSep 20, 2016 at 4:50
James Henry's user avatar

Comments

0
#This is the same code as the one above it's just without comments#This program takes a number from the user and turns it into an 8bit binary stringinteger_number = int(input('Please input an integer'))result = ''  for x in range(8):    r = integer_number % 2     integer_number = integer_number//2    result += str(r)result = result[::-1]print(result)
answeredNov 15, 2013 at 23:02
Mixstah's user avatar

2 Comments

You might want to elaborate on your answer some more. People tend to ask questions to learn and not just get an answer.
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.
0

here is a code that works in python 3.3.0 the converts binary to integer and integer to binary, JUST COPY AND PASTE!!!

def B2D():    decnum = int(input("Please enter a binary number"), 2)    print(decnum)    welcome()def D2B():    integer_number = input('Please input an integer')    integer_number = int(integer_number)    result = ''      for x in range(8):        r = integer_number % 2        integer_number = integer_number//2        result += str(r)    result = result[::-1]    print(result)    welcome()def welcome():    print("*********************************************************")    print ("Welcome to the binary converter program")    print ("What would you like to do?")    print ("Type 1 to convert from denary to binary")    print ("Type 2 to convert from binary to denary")    print ("Type 3 to exit out of this program")    choice = input("")    if choice == '1':        D2B()    elif choice == '2':        B2D()    elif choice == '3':        print("Goodbye")        exitwelcome()
answeredFeb 18, 2014 at 22:36
Will.B's user avatar

Comments

0

I give thanks to nikpod. His code helped me give out my own answer.Hope this helps.

# Define your functions here.def int_to_reverse_binary(num):    string = ''    while num > 0:        string += str(num % 2)         num = num // 2    return string    def string_reverse(string_to_reverse):       return string_to_reverse[::-1]if __name__ == '__main__':    # Type your code here.     # Your code must call int_to_reverse_binary() to get     # the binary string of an integer in a reverse order.    # Then call string_reverse() to reverse the string    # returned from int_to_reverse_binary().    num = int(input())    binary = int_to_reverse_binary(num)    print(string_reverse(binary))
answeredApr 1, 2022 at 13:59
Python4Me's user avatar

Comments

0

Sheesh some of these examples are very complicated for a Python noob like me.
This is the way I did the lab(Please let me know what you think):

First, the way the lab wants to see it is in reverse(not correct binary but that's the way the lab wants to see it):

x = int(input())bin_number = ''while x > 0:    result = x % 2    bin_number = str(bin_number) + str(result)    x = x // 2    if x < 1:        break    continueprint(bin_number)

Second, prints the result in the correct order(but incorrect for the lab)

x = int(input())bin_number = ''while x > 0:    result = x % 2    bin_number = str(bin_number) + str(result)    rev_bin_number = bin_number[::-1]    x = x // 2    if x < 1:        break    continueprint(rev_bin_number)
answeredOct 25, 2022 at 16:52
Justthefacts's user avatar

1 Comment

What is this lab you are talking about? The question didn't mention a lab.

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.