Decimal to binary c++ code example
Example 1: convert binary to decimal c++ stl
string bin_string = "10101010";
int number =0;
number = stoi(bin_string, 0, 2);
Example 2: 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 3: convert int to binary string c++
std::string str = std::bitset<8>(123).to_string();
Example 4: 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;
}