user2833230
user2833230

Reputation: 11

Data Representation

We can implement decimal to binary conversion for positive integers in Python by using the following algorithm that takes an integer n as input and returns a string of 1's and 0's holding the binary representation of n .

Write a function int_to_bin_string(n) (in int_to_bin_string.py) which takes a non-negative integer n and returns the a string of 1's and 0's.

We are not allowed to use any built in python functions that converts numbers to strings or vice versa.

    def int_to_bin_string(n):
        if n == 0:
            return "0"
        s = ''
        while n > 0:
            if n % 2 == 0:
                ch = "0"
            else:
                ch = "1"
            s = s + ch
            n = n/2
        return s

That's what I have tried. When I try int_to_bin_string(255) I get '1', instead of '11111111'

It works now!

Upvotes: 1

Views: 556

Answers (5)

Mike Housky
Mike Housky

Reputation: 4069

I'll bet a nickel, from the symptoms, that this is a Python 3 vs. Python 2 issue. Your code as modified works fine on Python 2.

You can make this code bilingual with a simple modification. Replace the division by 2 with a shift. In place of n = n/2, use n = n>>1. That works on both P2 and P3.

def int_to_bin_string(num):
    n = int(num) # added to force int type on entry
    if n == 0:
        return "0"
    s = ''
    while n > 0:
        if n % 2 == 0:
            ch = "0"
        else:
            ch = "1"
        s = s + ch
        n = n >> 1 # was n/2
    return s

I also added a small filter to coerce the argument to int on entry, with a rename to avoid losing the original argument value. When debugging, I like see the original value--hence the rename. I just do that as reflex; it's not related to your question.

Upvotes: 0

Nicholas Feix
Nicholas Feix

Reputation: 154

This could be an alternative for you... it's almost the same though

def int_to_bin_string(n):
    s = ''
    while n:        
        s = ((n & 1) and "1" or "0") + s
        n >>= 1
    return s or "0"

I hope this does help ;)

Upvotes: 0

Nicholas Feix
Nicholas Feix

Reputation: 154

You could use a key function of python

bin( value ) # returns a string like '0b110110'

simply get a slice if you only want the numbers... bin( value )[2:]

Upvotes: 0

eliotn
eliotn

Reputation: 300

You have a premature return in return s. It needs to be outside your while loop, which is why you are getting only one character. Also it should be n = n/2.

Additionally, look at your first return statement, it returns an integer instead of a string.

Upvotes: 0

prgao
prgao

Reputation: 1787

for the second to last line, you need to have

n = n/2 

Upvotes: 1

Related Questions