how to convert decimal number to binary

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • vmpstr
    New Member
    • Nov 2008
    • 63

    #31
    I prefer looping over the number of bits and doing a check along the lines of
    Code:
    if ( num & (1 << curbit) )
    If that is true, then bit curbit is set (the least significant bit being bit 0). This is very similar to what weaknessforcats said, except that one is

    Code:
    if ( (num >> curbit) & 1 )
    :D

    Comment

    • YarrOfDoom
      Recognized Expert Top Contributor
      • Aug 2007
      • 1243

      #32
      I believe itoa() with base 2 would be kinda spoiling the fun.
      That, and you don't learn anything from it.

      Comment

      • bcaparna
        New Member
        • Aug 2010
        • 1

        #33
        Here,a much easier way to convert decimal in to base-2,8,16-
        Code:
        // this program converts the given decimal number into to the desired bases.
        #include<iostream.h>
        #include<conio.h>
        #include<math.h>
        
        void main()
        {
         clrscr();
         int i, a[1], b, n;
         char ch;
         do
         {
          cout<<"Enter the Decimal Number to be converted: \n";
          cin>>n;
          if(n<0)
           {
             cout<<"Enter a Positive Number: \n";
           }
          else
           {
             cout<<"Enter the Base(2, 8 or 16): \n";
             cin>>b;
             if(b!=2 && b!=8 && b!=16)
                    {
                    cout<<"Invalid Base!"<<endl;
                    }
                    else
                    {
                    i=7;
                        do
                        {
                         a[i]=n%b;
                         n=n/b;
                         i--;
                        }
                        while(n>0);
                        while(i>=0)
                        {
                         a[i]=0;
                         i--;
                        }
                        for(i=0;i<=7;i++)
                        {
                         if (a[i]==10)
                         cout<<"A";
                         if (a[i]==11)
                         cout<<"B";
                         if (a[i]==12)
                         cout<<"C";
                         if (a[i]==13)
                         cout<<"D";
                         if (a[i]==14)
                         cout<<"E";
                         if (a[i]==15)
                         cout<<"F";
                         else
                         cout<<"\t"<<a[i];
                        }
                    };
           }
          cout<<"\nDo you wish to convert another number? (y/n)"<<endl;
          cin>>ch;
         }
         while(ch!='n');
         getch();
        }
        Last edited by Niheel; Aug 7 '10, 07:15 PM. Reason: added code tags to code

        Comment

        Working...