int to binary c++ code example
Example 1: convert decimal to binary in c++
#include <iostream>
using namespace std;
void decToBinary(int n)
{
int binaryNum[32];
int i = 0;
while (n > 0) {
binaryNum[i] = n % 2;
n = n / 2;
i++;
}
for (int j = i - 1; j >= 0; j--)
cout << binaryNum[j];
}
int main()
{
int n = 17;
decToBinary(n);
return 0;
}
Example 2: convert int to binary string c++
std::string str = std::bitset<8>(123).to_string();
Example 3: how to do decimal to binary converdsion in c++
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
int main() {
vector<int>nums;
int num = 0;
cout<<"Number: "<<endl;
cin>>num;
int i=0;
while(num!=0)
{
nums.push_back(num%2);
i++;
num=num/2;
}
reverse(nums.begin(),nums.end());
for(auto x:nums)
{
cout<<x;
}
return 0;
}