## DEV Community is a community of 753,853 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Scott Gordon

Posted on

# Decimal to Binary

``````# decimal_to_binary.py
#   This program converts a decimal number to binary using a stack.
# by: Scott Gordon

from stack import Stack

def convert_int_to_bin(dec_num):

if dec_num == 0:
return 0

s = Stack()

while dec_num > 0:
remainder = dec_num % 2
s.push(remainder)
dec_num = dec_num // 2

bin_num = ""
while not s.is_empty():
bin_num += str(s.pop())

return bin_num

print(convert_int_to_bin(56))
print(convert_int_to_bin(2))
print(convert_int_to_bin(32))
print(convert_int_to_bin(10))

print(int(convert_int_to_bin(56),2)==56)
``````
``````"""
Stack Data Structure.
"""

class Stack:
def __init__(self):
self.items = []

def push(self, item):
self.items.append(item)

def pop(self):
return self.items.pop()

def is_empty(self):
return self.items == []

def peek(self):
if not self.is_empty():
return self.items[-1]

def get_stack(self):
return self.items
``````

Photo by Alexander Sinn on Unsplash

## Discussion (2)

Łukasz Żmudziński

Python has a function that does this for you 🙂.

``````bin(value)
``````

If you want to ditch the `0b`, then you can just do the following:

``````bin(value)[2:]
``````
Scott Gordon

Yes, I was aware of this. But thank you just the same for your feedback. Sometimes I brute force things just to see if I can figure them out without a library.