I made a converter that takes a decimal number and converts it to binary but when I get to the conversion part the numbers dont print? Can somebody please help!
the first part of a for loop initialises... that is ok.. it is already initialised
the last part is the change every round... also ok.
but the middle one needs to be true as long as you want to loop to continue...
and x is not zero when you start, so the loop will never execute...
and further more...
usingnamespace std;
place it once above main under includes.. not inside functions...
And maybe you can rethink your whole idea.
it is a lot of code for a simple task..
#include "stdafx.h"
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
cout<<"Please enter a number to be converted to binary: ";
int number;
cin>>number;
string bitVal = "";
while (number != 0)
{
if (number & 1)
{
bitVal += "1";
}
else
{
bitVal += "0";
}
number = number >> 1;
}
cout << bitVal;
return 0;
}
#include "stdafx.h"
#include <iostream>
#include <string>
usingnamespace std;
void rev_str(string str,int n);
int main()
{
cout<<"Please enter a number to be converted to binary: ";
int number;
cin>>number;
string bitVal = "";
while (number != 0)
{
if (number & 1)
{
bitVal += "1";
}
else
{
bitVal += "0";
}
number = number >> 1;
}
bitVal = string(bitVal.rbegin(), bitVal.rend());
cout<<"The binary number is: "<<bitVal<<endl;
return 0;
}
You can still optimized and smarter in code
for example
main()
{
int decimal, reminder, i = 1, binary = 0;
cout< <"Enter the decimal to be converted:"<<endl;
cin>>decimal;
do
{
reminder = decimal % 2;
binary = binary + (i * reminder);
decimal = decimal / 2;
i= i * 10;
}while(decimal > 0);
cout< <"The binary of the given number is:"<<binary<<endl;
getch();
}
I fixed the backwards issue by reversing the string.
this is like writing CBA and copying you work to ABC..
it is to much work...
just to this:
1 2 3 4 5 6 7 8 9 10 11 12 13
while (number != 0)
{
if (number & 1)
{
bitVal = "1" + bitVal ;
}
else
{
bitVal = "0" + bitVal ;
}
number = number >> 1;
}
and btw that is exaclty the same as what i had;)
1 2 3 4 5
while( a != 0 )
{
bitVal = (a & 1 ) ? "1" + bitVal : "0" + bitVal ;
a = a >> 1;
}
You can still optimized and smarter in code
smarter code?
the % operator is slow compared to & operator...
just use decimal & 1 it is much faster...
the same counts for / operator.. use decimal >> 1; instead...
and why do you use int to store the binary?
it has a max lenght compared to a string...