Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Help a newbie out

Name: Anonymous 2012-04-01 10:14

Hello /prog/, I need a help in understanding this code, anyone willing to explain it in detail to an idiot?


(decimal to binary number)
int main()
{
int dec,rem,i=1,sum=0;
    cout<<"Enter the decimal to be converted:"<<endl;
    cin>>dec;
    do
    {
        rem=dec%2;
        sum=sum + (i*rem);
        dec=dec/2;
        i=i*10;
    }while(dec>0);
    cout<<"The binary of the given number is:"<<sum<<endl;
 
}

Name: Anonymous 2012-04-01 10:57

let's try to help Mr. Opee
please don't flame me /prog/gers

rem=dec%2;
this fetches one binary digit (bit) from the number being converted, specifically the rightmost (least significant) one.
i hope you know what remainders are and what % does, else >>2-fu is right.

sum = sum + (i * rem);
i = i * 10;
this adds the fetched bit to the tally. we move left each time by multiplying i by 10 so that each bit is separate. for example:


    1 * 0 <-- first fetched bit
   10 * 1 <-- second fetched bit
  100 * 0 <-- etc.
+1000 * 1
----------
 = 1010   <-- a single decimal number displaying all the bits


dec = dec / 2;
this shifts the bits in the input number to the right so that we can get the next rightmost (least significant) bit and restart the loop. once we have shifted sufficiently, zero is reached and so the loop is breaked. this is because any number can be thought of as being prefixed by an infinity of zeroes:


 000000000000000123 = 123

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List