I'm a college student and I have recently started learning c . I learned few syntaxes and I wrote a code which converts a decimal number to binary.
#include <iostream>
#include <string>
using namespace std;
void main()
{
int num = 0, bit = 0, div = 0, i = 0;
string binary = "";
cout << "Enter a decimal number : ";
cin >> num;
div = num / pow(2, i);
while (div != 0)
{
bit = div % 2;
binary = to_string(bit) binary;
i ;
div = num / pow(2, i);
}
cout << "Binary of decimal " << num << " is : \n";
cout << binary;
}
Can someone guide me if this code can be further optimized or if I have used a functions which is advised not to use. Thanks
My results were what I expected it to be, but I dont know if there is something else I should have tried.
CodePudding user response:
std::string toBinaryString(int n)
{
if (n < 0){
if (n == INT_MIN){
// Negation of INT_MIN is UB on 2's complement systems.
// Needs to be handled separately.
return "Something";
}
return "-" toBinaryString(-n);
} else if (n > 0){
std::string s;
while (n){
s = (n % 2 ? "1" : "0") s;
n /= 2;
}
return s;
} else {
return "0";
}
}
is one way. It burns the CPU a little with the string prepending but the number of times that happens is binary logarithmic on n
. The specific handling of 0 is ugly, but really that stems from the fact that generating zero from any numeral system is a pain. (The Romans didn't come up with anything.) Don't forget to check the return value of cin >> num
in production code.
CodePudding user response:
A straightforward example of building up a string "backwards" from the smallest digit first using %
and /=
, and then using std::reverse
to reverse that string. Specifically does not deal with signed ints.
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
std::string convert_dec_to_bin(unsigned int dec) {
if (dec == 0) return "0";
std::stringstream ss;
while (dec > 0) {
ss << dec % 2;
dec /= 2;
}
auto result = ss.str();
std::reverse(result.begin(), result.end());
return result;
}
int main() {
unsigned int num;
std::cin >> num;
std::cout << convert_dec_to_bin(num) << std::endl;
return 0;
}
CodePudding user response:
You have to include math.h
library and after i
use this line div = div / 2
CodePudding user response:
It's better to have div
as a running total instead of calculating it afresh from num
each time
So
div = num;
while (div != 0)
{
bit = div % 2;
binary = to_string(bit) binary;
i ;
div = div / 2;
}
This avoids the problems that can happen when using pow
for integer powers, and is more efficient as well.