Reputation: 6544
I am well aware that there are some duplicated questions on this topic, though each that I find do not resolve my issue. For one I can not use any special libraries besides the iostream
, iomanip
, and string
. So what I have so far is this
int DecToBin(int num)
{
int bin = 0;
while (num > 0)
{
bin += (num % 2);
//cout << bin << endl; this is used for debugging purposes
num = num / 2;
}
return bin;
}
And I call it like so
int binary = DecToBin(170);
cout << binary << endl;
Except I keep getting 0, which I believe is because of the data type I set it too. So my question is how do I get the correct output to come? Also my results should be
10101010 is base 10 of 170
Upvotes: 0
Views: 998
Reputation: 44238
As @Cyber's answer technically fixes the issue, I think it would not hurt to explain your misunderstanding. Your function DecToBin
does not convert decimal to binary, but rather binary to some strange binary format which being printed as decimal gives you binary representation. Problem is that numbers already stored in binary format and it was converted to binary either by translator (if you used constant in your source code) or by io library, if you used std::cin
to input. The same library converts it back to decimal (by default) from binary when you print it on the console using std::cout
, which leads to your idea, that number is stored in decimal format.
So technically your solution works but I am not sure that your professor would accept it as it shows that you do not understand the concept (I would not). Proper solution would be to convert int to binary string and then output it to std::cout
:
std::string binary( unsigned int n )
{
std::string s;
for( ; n > 0; n /= 2 )
s = std::to_string( n % 2 ) + s;
return s;
}
int main()
{
int n = 170;
std::cout << "binary representation of " << n << " is " << binary( n )
<< std::endl;
}
Upvotes: 1