hi. how can a decimal value be converted to binary in a c++ program?

Recommended Answers

All 4 Replies

Division by two with reminder.
divide % the number by two till reaches Zero if the reminder is no-zero, save 1 else save 0.
then write binary number from button to above.

now you can write the code easily with forloop and if statement.

commented: plz send me the code +0
void printBinary(char ch) noexcept {
    for(int i = 7; i >= 0; --i)
        if(ch & (1 << i)) std::cout << "1";
        else std::cout << "0";
}

int main() {
    int num = 56;
    std::cout << std::endl;
    printBinary(num);
    std::cout << std::endl;
    return 0;
}


return 0;

The easiest way is to use bitset

#include <iostream>       
#include <bitset>      

int main ()
{
  std::bitset<16> foo(123);
  std::cout << foo << '\n';
  return 0;
}

Mine is a bit too much using just simple for and if loops

#include<iostream>
#include<stdlib.h>

using namespace std;

int main()
{
int a[16]={0},b,i=0;
cout<<"\n Enter the number to be converted to binary";
cin>>b;
if(b==0)
{
cout<<"\n 0000";
exit(1);
}
while(b!=0){
a[i]=b%2;
b/=2;
i++;
if(b==1)
   {
    a[i]=1;
    break;
   }
}
for(int j=i;j>=0;j--)
    cout<<a[j];
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.