DEV Community

Cover image for Decimal to Binary
Scott Gordon
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)
Enter fullscreen mode Exit fullscreen mode
"""
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
Enter fullscreen mode Exit fullscreen mode

Photo by Alexander Sinn on Unsplash

Discussion (2)

Collapse
lukzmu profile image
Łukasz Żmudziński

Python has a function that does this for you 🙂.

bin(value)
Enter fullscreen mode Exit fullscreen mode

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

bin(value)[2:]
Enter fullscreen mode Exit fullscreen mode
Collapse
sagordondev profile image
Scott Gordon Author

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.