Binary Deployment Help

Not much to say. After much Googling, I created a function that I thought would work. It does not work

def decToBin(number):
    binary = []
    while number > 0:
        if number % 2 != 0:
        if binary % 2 == 0:
        number = number / 2
    if number == 0 and len(binary) < 8:
    if len(binary) == 8:

I put the self.say in there to check the function, but my hero never says anything. Can anyone give me a small hint that will put me on the path to fix my code? I feel like I’m on the right track, but I just can’t figure it out.

Your binary.reverse() line is not valid: strings in python are immutable (=cannot change) and they don’t have reverse method.

The reversed function (not reverse!) returns a list, so you need to join it to become a string again: "".join(reversed(your_string))

Thus, you would need to do the following

#        binary.reverse()        # remove this line

or, use python’s advanced slice:


Don’t you just love python? :smile:

I didn’t check the rest of your code, but if you divide a positive number by 2 (or any other positive number), the result will always be greater than zero… so you have an infinite while loop there…

So I updated and simplified my code, but it still doesn’t work.

def decToBase(digits, base):
    newSet = []
    while len(newSet) < 8: 
        rem = digits % base
        digits = digits // base
    return newSet

Seems simple enough to me. Take the decimal number and get the remainder when dividing by the base. Append the remainder to the array. Then divide the number by two. Do that until the array has a size of 8. But when I add a self.say in to check it, the array is filled with NaN. What am I doing wrong?

EDIT: Well I found my own problem. The digits = digits // base seems to break the function. But I don’t understand why. I was able to find a workaround that made my code work, but I’d love to know why the original code in this comment didn’t work.