|
-
July 19th, 2004, 11:43 AM
#16
Just for your interest, here's a program I wrote last night to convert decimal to binary. It lets you specify the number of bits that you want to use (that's kinda pointless really, but I felt like putting it in for a change :P) I'm just posting this to let you see what I was meaning about the while loop.
Note that I used cout in my code. That's just a c++ object that works similar to printf. Just ignore it and the "using namespace std;" bit at the top. It's the other code that should be of interest. Also, note that I attempted to use meaningful variable names; you need to try not to call your variables "a", "b", "c", etc.
Code:
#include <iostream>
#include <math.h>
#include <stdlib.h>
using namespace std;
int main(int argc, char **argv)
{
int number = 0;
int bits = 0;
int count = 0;
if(argc<3)
{
cout << "Usage: " << argv[0] << " [number] [bits]\n" << endl;
cout << "number - the number to be converted" << endl;
cout << "bits - the number of bits to be used" << endl;
return(0);
}
// the next two lines take strings as input and convert them to integers
// for more info on argv[2], etc. look for a tutorial on command line parameter passing
bits = atoi(argv[2]);
number = atoi(argv[1]);
int orignum = number; // create a copy of the original number for the end
// you can pretty much ignore this bit, but if you're interested, there's a note at the
// end of the post.
if((pow((double)2,(double)bits)-1)<number)
{
cout << "ERROR: too few bits used to display number." << endl;
return(0);
}
int binarray[bits];
for(int x=0; x<bits; x++)
binarray[x] = 0; // just making sure binarray is initialised to 0
while(number!=0) // keep looping until we cannot do any more calculations
{
binarray[count] = number % 2;
number=number/2;
count++;
}
cout << orignum << " is ";
for(int x=(bits-1); x>=0; x--) // output binarray backwards
cout << binarray[x];
cout << " in binary" << endl;
return(0);
}
Hope that's of some interest to you.
ac
[edit]NOTE: double pow(double x, double y) is a method that takes a double x, raises it to the power double y and returns the answer as a double. If you do a "man pow" on your slackware box you'll get a list of all the different pow functions.
If you know your binary, you'll understand that the maximum number that 4 bits can store is (2^4)-1 (note that 2^4 takes 5 fingers to count because we count the zero :P) so that means that with 4 bits, the highest number that you can store is 15.[/edit]
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
|