5
Contributors
4
Replies
54
Views
4 Years
Discussion Span
Last Post by Sam_6
1

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.

Votes + Comments
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;
2

The easiest way is to use bitset

#include <iostream>       
#include <bitset>      

int main ()
{
  std::bitset<16> foo(123);
  std::cout << foo << '\n';
  return 0;
}
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];
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.