First of all, the above code you have pasted has lots of indentation issues, next time you should try to fix those indentation issues and running your program again, before posting it here.

Secondly, your logic is also wrong, you should not be checking -

while newNum == 1:

at start itself, you are setting newNum = decNum , unless you enter 1 , your program would not enter that while loop. The condition you need is -

while decNum != 0:

Secondly, the second while loop, should not be inside the first while loop, it should be outside, so that you print out the stack once all the computation is complete. Also , you don't even need the first newNum = decNum , before the loop starts.

I fixed all your indentation issues, and logical issues, the code is -

import sys
class Stack ():
    def __init__(self):
        self.items=[]
    def push (self,item):
        self.items.append(item)
    def pop (self):
        return self.items.pop()
    def size(self):
        return len(self.items)
s1= Stack()
decNum= int(raw_input("Enter the decimal num : "))
while decNum!=0:
    newNum= decNum%2
    decNum = decNum//2
    s1.push(newNum)
while s1.size() != 0:
    a=s1.pop()
    sys.stdout.write(str(a))
sys.stdout.flush()
Answer from Anand S Kumar on Stack Overflow
Discussions

python - Decimal to binary algorithm - Code Review Stack Exchange
Is there a better way to code this specific algorithm using successively division through 2 which converts decimal numbers into binary numbers without calling a built-in function? print "Please en... More on codereview.stackexchange.com
🌐 codereview.stackexchange.com
July 7, 2016
python - Decimal to binary using stack but not sure how the input should be a stack itself - Stack Overflow
I do not understand the concept of how I can pop an integer from a stack and convert it into binary. I successfully created a program that can take in an integer and convert it to binary by pushing... More on stackoverflow.com
🌐 stackoverflow.com
How Convert decimal to binary using stack?
Decimal to Binary Using a StackThere is no need to program a computer to convert from decimal to binary because all programming languages do this by default; they are binary computers after all. That is, if we want to store the decimal value 42 in computer memory, we simply assign the literal ... More on math.answers.com
🌐 math.answers.com
2
3
April 23, 2011
Python: Decimal to Binary - Stack Overflow
I'm trying to get the function to work, it is suppose to convert Decimal to Binary but all it gives me different numbers instead. Like if I enter 12, it would give me 2. I'm not sure where in the c... More on stackoverflow.com
🌐 stackoverflow.com
🌐
KSoftLabs
ksoftlabs.com › home › converting decimal numbers to binary numbers using stacks
Converting Decimal Numbers to Binary Numbers Using Stacks - KSoftLabs
July 14, 2017 - class Stack: def __init__(self): self.items = [] #create new list with no items def __repr__(self): return repr(self.items) #define what to return is the stackname is called def isEmpty(self): return self.items == [] #check whether list if empty and retuen T or F def size(self): return len(self.items) #return size of stack (= length of list) def push(self,val): self.items.append(val) #add the argument pass to the end of list def pop(self): return self.items.pop() #return the last item in list because index not specified def peek(self): return self.items[-1] #return last item (-1 because from r
🌐
Quora
quora.com › How-can-I-write-a-Python-program-using-stack-to-convert-binary-to-a-decimal
How to write a Python program using stack() to convert binary to a decimal - Quora
Answer (1 of 2): EDIT: Quora is left placing the whole answer. Please mind the indentations as they are block equivalent of ‘C’ in python. Try this. The logic is 1.To assign and divide the decimal number by 2 until it becomes zero. 2.Storing the remainder in the stack. 3.Printing it in the r...
Top answer
1 of 1
8

In general, your idea is not bad.

The best solution, as far as I read, would be the algorithm Divide by 2 that uses a stack to keep track of the digits for the binary result.

As an intro, this algorithm assumes that we start with an integer greater than 0. A simple iteration then continually divides the decimal number by 2 and keeps track of the remainder.

The first division by 2 gives information as to whether the value is even or odd. An even value will have a remainder of 0. It will have the digit 0 in the ones place. An odd value will have a remainder of 1 and will have the digit 1 in the ones place. We think about building our binary number as a sequence of digits; the first remainder we compute will actually be the last digit in the sequence.

That said, we have:

from pythonds.basic.stack import Stack

def divideBy2(decNumber):
    remstack = Stack()

    while decNumber > 0:
        rem = decNumber % 2
        remstack.push(rem)
        decNumber = decNumber // 2

    binString = ""
    while not remstack.isEmpty():
        binString = binString + str(remstack.pop())

    return binString

print(divideBy2(42))

Comments regarding your code:

  1. Why did you do this: dec_new = dec_number ? You could've just use dec_number. There's no need of assigning its value to another variable.
  2. This: dec_new = dec_new // 2 could be as well as the above line of your code rewritten as: dec_new //= 2
  3. The indentation should contain 4 spaces, not 2.

A version that better (than your solution) utilizes the memory would be:

def dec_to_bin(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)

What I did:

  • floor divide all the numbers by two repeatedly until we reach 1
  • going in reverse order, create bits of this array of numbers, if it is even, append a 0 and if it is odd append a 1.

Other ways of doing it:

Using recursion:

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

The above solution returns the result as a list which you can later on .join() then apply int() to it.

Another idea that came to my mind is as simple as:

u = format(62, "08b")
>> 00111110
🌐
YouTube
youtube.com › quinston pimenta
Decimal To Binary using Stack | Code Tutorial - YouTube
The Code can be found at: https://quinston.com/code-snippets https://github.com/graphoarty If you like and support this content, you don't need to give me an
Published: January 9, 2014
Views: 5K
🌐
Stack Overflow
stackoverflow.com › questions › 78400590 › decimal-to-binary-using-stack-but-not-sure-how-the-input-should-be-a-stack-itsel
python - Decimal to binary using stack but not sure how the input should be a stack itself - Stack Overflow
You don't need a stack for that. Instead, keep track of the power-of-10 that you want the current bit from the input to represent. For example, if the input is eleven, which in binary is 1011, then the translation is as follows:
Find elsewhere
🌐
CodeChef
codechef.com › learn › course › stacks-and-queues-new › STACKQUE02 › problems › STACK06
Convert Decimal to Binary in Stacks and Queues
Test your Learn Stacks and Queues knowledge with our Convert Decimal to Binary practice problem. Dive into the world of stacks-and-queues-new challenges at CodeChef.
🌐
Answers
math.answers.com › engineering › How_Convert_decimal_to_binary_using_stack
How Convert decimal to binary using stack? - Answers
April 23, 2011 - Right-shift (>>) the binary value by 3 bits and repeat until the binary value is zero. Pop the stack to build the left-to-right digits of the octal value. Using 10110100 as an example: 10110100 & 00000111 = 00000100 10110100 >> ...
🌐
YouTube
youtube.com › watch
Data Structures in Python: Stack -- Convert Integer to Binary - YouTube
Problem: Use a stack data structure to convert integer values to their corresponding binary representation. This video is part of the "Data Structures" serie...
Published: May 5, 2017
🌐
GeeksforGeeks
geeksforgeeks.org › python-program-to-covert-decimal-to-binary-number
Convert Decimal to Binary Number - GeeksforGeeks
Explanation: In each iteration, the remainder (n % 2) is prepended to res, building the binary representation until n becomes zero. Recursion method uses a divide-and-conquer approach by repeatedly dividing the decimal number by 2. The recursive function continues until the number is reduced to 1. This method is elegant but less efficient due to the function call stack.
Published: March 19, 2025
🌐
Runestone Academy
runestone.academy › ns › books › published › pythonds › BasicDS › ConvertingDecimalNumberstoBinaryNumbers.html
4.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures
The “Divide by 2” idea is simply replaced with a more general “Divide by base.” A new function called baseConverter, shown in ActiveCode 2, takes a decimal number and any base between 2 and 16 as parameters. The remainders are still pushed onto the stack until the value being converted ...
🌐
Google Sites
sites.google.com › site › advancedpythonprogramming › basic-data-structures › converting-decimal-to-binary
Advanced Python Programming - Converting Decimal to Binary
But how can we easily convert integer values into binary numbers? The answer is an algorithm called “Divide by 2” that uses a stack to keep track of the digits for the binary result.
🌐
Runestone Academy
runestone.academy › ns › books › published › pythonds3 › BasicDS › ConvertingDecimalNumberstoBinaryNumbers.html
3.8. Converting Decimal Numbers to Binary Numbers — Problem Solving with Algorithms and Data Structures 3rd edition
The “Divide by 2” idea is simply replaced with a more general “Divide by base.” A new function called base_converter, shown in ActiveCode 2, takes a decimal number and any base between 2 and 16 as parameters. The remainders are still pushed onto the stack until the value being converted ...
🌐
Stack Overflow
stackoverflow.com › questions › 60944216 › why-is-my-python-code-to-convert-an-number-to-binary-using-stack-not-working
Why is my python code to convert an number to binary using stack not working? - Stack Overflow
You must store the top element in a variable and then pop the stack after it. ... def binary(n): b = Stack() while n > 0: r = n % 2 b.push(r) n = n//2 print(b.stack) bn = '' while not b.empty(): bn += str(b.stack[-1]) b.pop() return bn
🌐
Reddit
reddit.com › r/learnpython › converting from decimal to binary in python
r/learnpython on Reddit: Converting from decimal to binary in Python
July 24, 2019 -

Would someone be willing to help me (total beginner) understand how this converts decimal values to binary? Maybe just by explaining what happens line by line?

def dec2bin(n):
    if n > 1:
        dec2bin(n//2)
    print(n % 2, end="")

It's just not intuitive at all for me :/

Any help would be greatly appreciated!

Top answer
1 of 4
19
So this is a pretty complicated topic for a beginner called recursion. I'll try my best to explain what's going on. The last line print(n % 2, end="") simply prints the remainder after n is divided by 2. This will be either 1 or 0 since 2 goes into all larger numbers atleast once. By default python puts a new line character after every print and the 'end=""' simply says 'print nothing at the end' instead of the normal 'print \n at the end' (\n indicates a newline) Now for the fun part. Let's step through what happens with n=10. In binary we know this is represented by '1010'. When n is 10 we see it is greater than 1, so we execute line 3 (dec2bin(n//2)). This basically pauses what we're currently doing for now and starts over with a different value. You can think of this like a stack of boxes. Originally we just have our one box, when we call dec2bin again we put another box on top. We can't keep working on the bottom box anymore because it's covered. We need to finish the top box so we can remove it and get to the bottom box again. I should mention that // means integer division. 3//2 is 1 because 2 goes into 3 one whole time. So in our stack of boxes (aka our call stack) we will have: dec2bin(5) dec2bin(10) So let's work through what happens when we call dec2bin(5). It's important to note that 5 is '101' in binary which is the same as 10 ('1010') except the last 0 disappears because of the division. 5 is greater than 1 so we execute line 3 and call dec2bin again! Gotta put another box on top of our call stack: dec2bin(2) dec2bin(5) dec2bin(10) Note that 2 in binary is '10', which is the same as ten in binary except drop the last two digits because we did division twice. Working through dec2bin(2) we get another call to dec2bin: dec2bin(1) dec2bin(2) dec2bin(5) dec2bin(10) Printed: nothing Now this is where it gets interesting. Working through dec2bin(1) we have n=1. In this case n is NOT greater than 1 (line 2). So we continue on and print 1%2 which is 1. Now the function finishes and we're done with this call of dec2bin(1) so we can remove it from the call stack: dec2bin(2) dec2bin(5) dec2bin(10) Printed: '1' Now dec2bin(2) we paused on line 3, but line 3 just finished up so we can continue onto line 4 and print 2%2 which is 0. We've printed '10' so far. Again the function finishes up and we remove it from the call stack. dec2bin(5) dec2bin(10) Printed: '10' dec2bin(5) was paused on line 3, it continues now. We print 5%2 which is 1. The function finishes. It gets removed from the call stack. dec2bin(10) Printed: '101' We've finished up most of the pile back down to our original call. It (finally) runs its line 4 and prints 10%2, which is 0. We've printed '1010'. The function finishes up and we're all done. Printed: '1010' I hope that I haven't just confused you further, recursion is a tough topic to understand especially if not explained in a way that makes sense to you.
2 of 4
1
Let's break it down line by line: if n > 1: - since 0 and 1 are already "in" binary - we don't need to do anything. This will serve as a final step for the code (i.e., if dec2bin gets a 0 or 1 - it will print a 0 or 1, respectively). dec2bin(n//2) - if the number n is larger than 1, we recursively call the function again on the floor of the result of dividing n by 2. For example, if n = 5 we'll get 5//2 = 2. This will keep going until the result of the division's floor is either 0 or 1. print(n % 2, end="") - first, we need to remember that the modulo operator a % b will return the remainder of the division of a by b. For our example with n = 5, we'll get 1. Finally, the new="" will append an empty string to the end of our string, instead of the default new line. This means we'll keep printing to the same line in the output. We can use something like Python Tutor to visualize this, in the link I've written it for n = 5. I'll also try to explain it in words. Let's take the case of n = 5: First, we call dec2bin(5) - since 5 > 1, we execute the code in the if block - so we call dec2bin(5//2), i.e. dec2bin(2). Now we're inside dec2bin(2) - again, we have 2 > 1. This time we call dec2bin(2//2) which is dec2bin(1). Now we're inside dec2bin(1) - since 1 = 1, we move straight to the print line. We print the remainder of 1 / 2, i.e. 0. The printed output will now be "1". Since we finished running the code in dec2bin(1) we're back in dec2bin(2). Again, we're at the print line, so we print 2 % 2 = 0. The printed output will now be "10". We've finished with dec2bin(2), so we're back in dec2bin(5). This time, we print 5 % 2 = 1. This is the end of the program, and the printed output will now be "101", which is indeed (1*2^0 + 0*2^1 + 1*2^2 =) 5 in binary.
🌐
Blogger
linuxdiaryblog.blogspot.com › 2021 › 08 › convert-decimal-integer-to-binary-using.html
Linux Diary: Convert Decimal Integer to Binary using Stack
The while loop on the very next line executes if the stack s is not empty. If s is not empty, we pop a value from s and append it to the bin_num string on line 15. We keep popping elements from s until it becomes empty and the while loop is terminated. The bin_num is returned from the function on line 17. The following code helps us to evaluate whether our implementation is correct or not: ... The above statement will print True if convert_int_to_bin(56) returns the correct binary equivalent for 56.