Archived

This topic is now archived and is closed to further replies.

Chimaera

C++ Program

Recommended Posts

I was reading an older book on Computer Science that gave programming assignments after each "lesson". One of the first assignments was to write a program which, (a) inputs a binary string with an embedded radix point (e.g.: 101.101) (a floating point variable, right?) that outputs its decimal equivalent (e.g.: 5.625); (b) does the opposite of that effect; or inputs a decimal number and outputs its binary equivalent. Could anyone help me figure out how to implement this in C++? // Chimaera "C:\DOS C:\DOS\RUN \RUN\DOS\RUN"

Share this post


Link to post
Share on other sites
The easiest way to get started on a problem like this is to remember that the number 101.101 in binary can be represented as:
1*2^2 + 0*2^1 + 1*2^0 + 1*2^-1 + 0*2^-2 + 1*2^-3

You can use this information to break down your conversion into just a bunch of additions. Then you could just loop through the number that is input and add the corresponding value that each bit represents to a running total.

For example, it is probably easiest to start from the decimal point and work left and right. Essentially, you end up going "Is the 2^x position 'on'? If so, add 2^x to our total so far. Now increment x (assuming you are working to the left of the decimal) and repeat". Then, take the total and repeat the process starting from x=-1 and decremementing x until you run out of digits.

I wish I had time to give a better explanation or to help you with converting the other way, but hopefully that will get you started. Good luck!

Edited by - jaxson on June 10, 2001 7:17:08 PM

Share this post


Link to post
Share on other sites