Greetings everyone. This is my first post on this board, and I would like to offer thanks for any and all help, guidance, advice, and/or bonks on the head in advance. I am an aspiring programmer currently learning Python as a way to introduce myself to the world of software engineering.

I am attempting to create an algorithm that will convert a user input real (ie. XXXX.XXXX) decimal (ie base10) number to its binary equivalent. I have no trouble converting the integral part, but I cannot seem to come up with a functioning algorithm for the fractional part.

Below I have pasted what I have come up with so far for this portion of the script:

fractionstring = ""
mystring = "486.654321"
mysplit = mystring.split(".")
myfractional = float(mysplit[1]) / (10 ** len(mysplit[1]))
while myfractional < 1:
    binaryfraction = (myfractional * 2) // 1
    fractionstring = fractionstring + str(binaryfraction)
    myfractional = (myfractional * 2) - binaryfraction

If anyone could provide some advice to get me pointed in the right direction I would be much obliged.

EDIT: the <mystring> variable is initialized purely for testing purposes. In the final code I plan on using

raw_input("")

to retrieve input from the user.

Recommended Answers

All 6 Replies

I realize this must seem like an incredibly simple problem to most of the more experienced folks on this board, but this is my first experience with programming; as you can most likely tell I have a great deal to learn, and DaniWeb seems like a great resource for someone such as myself. Thanks again.

Right then, here is my updated code to perform the entire algorithm (convert a real decimal number to its binary equivalent):

integerstring = ""
fractionstring = ""
myinput = raw_input("Enter the real number you would like to convert to binary: ")
mysplit = myinput.split(".")
myinteger = int(mysplit[0])
myfraction = float(mysplit[1]) / (10 ** len(mysplit[1]))
print myinteger
print myfraction
while myinteger > 0:
    binaryinteger = myinteger % 2
    myinteger = myinteger / 2
    integerstring = str(binaryinteger) + integerstring

print integerstring

while myfraction < 1 and myfraction > 0:
    binaryfraction = myfraction * 2
    if binaryfraction > 1:
        fractionstring = fractionstring + "1"
        binaryfraction = binaryfraction - (binaryfraction // 1)
    elif binaryfraction < 1:
        fractionstring = fractionstring + "0"
    myfraction = binaryfraction
print fractionstring

print integerstring + "." + fractionstring

Does anyone have any thoughts, comments, or advice they would like to offer? I am still not sure about the fractional conversion part, but it *seems* to be working >.>

This is the final version. Thanks for humoring me.

x = 1
while x == 1:
    integerstring = ""
    fractionstring = ""
    myinput = raw_input("Enter the real number you would like to convert to binary: ")
    mysplit = myinput.split(".")
    myinteger = int(mysplit[0])
    myfraction = float(mysplit[1]) / (10 ** len(mysplit[1]))
    while myinteger > 0:
        binaryinteger = myinteger % 2
        myinteger = myinteger / 2
        integerstring = str(binaryinteger) + integerstring
    while myfraction < 1 and myfraction > 0:
        binaryfraction = myfraction * 2
        if binaryfraction > 1:
            fractionstring = fractionstring + "1"
            binaryfraction = binaryfraction - (binaryfraction // 1)
        elif binaryfraction < 1:
            fractionstring = fractionstring + "0"
        myfraction = binaryfraction
    if len(fractionstring) > 12:
        fractionstring = fractionstring[0:13]
    print integerstring + "." + fractionstring
    yesorno = raw_input("Would you like to continue? y/n : ")
    if yesorno == "y":
        pass
    if yesorno == "n":
        x = 0

Sorry, didn't see this thread before. I'm afraid it doesn't work ... :(

Enter the real number you would like to convert to binary: 3.1
11.0001100110011
Would you like to continue? y/n : y
Enter the real number you would like to convert to binary: 2.5
10.
Would you like to continue? y/n : y
Enter the real number you would like to convert to binary: 2.8
10.1100110011001
Would you like to continue? y/n : y
Enter the real number you would like to convert to binary: 4.25
100.0
Would you like to continue? y/n : n

As you can see, fractions like 1/2 and 1/4 don't get converted correctly.

Comments:

(1) This part is too complicated:

myinput = raw_input("Enter the real number you would like to convert to binary: ")
    mysplit = myinput.split(".")
    myinteger = int(mysplit[0])
    myfraction = float(mysplit[1]) / (10 ** len(mysplit[1]))

Replace with

myinput = raw_input("Enter the real number you would like to convert to binary: ")
mynum = float(myinput)
myint = int(mynum)
myfrac = mynum - myint

(2) Likewise, the conditional

if len(fractionstring) > 12:
        fractionstring = fractionstring[0:13]

is unnecessary. The slice will silently function correctly on strings less than 13 chars long.

Replace with fractionstring = fractionstring[:13]

(3) Your algorithm is basically the same one I would use, but there's a bug. If you think about it, your code for converting fractions to bin decimals is essentially the same (but inverted) as the code for converting integers -- so therefore, it ought to have roughly the same steps and length.

try this:

# convert the decimal part
output = "."
    myfrac = num - int(num)
    while myfrac > 0:
	myfrac *= 2
	if myfrac >= 1:
	    output += "1"
	    myfrac = myfrac - int(myfrac) # could also use myfrac %= 1
	else:
	    output += "0"

HTH,
Jeff

Jeff,

Thank you very much for the advice and for pointing out the errors in my code.

Once I have this script perfected and bug free I plan on writing an algorithm to convert a number to and from any base up to base62. I am not looking for examples or code samples, but I would be greatly interested in the thoughts of the DaniWeb community on how I should go about solving this problem. More specifically, I still have no idea how I am going to handle the letters as digits in bases higher than ten.

Once again thanks in advance!

EDIT: One thing I am considering trying RE: the letters as numerical values in bases above ten is using a dictionary with the letters (A through z) as keys ie.

dictionary = {"A": 10, "B": 11, "C": 12..."z": 61}

Does this seem like a reasonable method? If so, does anyone have advice on how to go about referencing the dictionary? I suppose using conditionals to determine if the user input contains a letter would be a good start...

If we're talking about readability, I would recommend using pairs of digits like clocks do:

1:35:48 (base 60)

means

1*60*60 + 35*60 + 48

The problem with using upper- and lower-case letters for different digits is that

(a) it's horrifically unreadable. Was that "a45Bc" or "a45bC"? Imagine this: "oO0oO0"

(b) Some poor schmoe is going to try for consistency and run .upper() on his numbers before converting them.

My $0.02
Jeff

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.