1,105,331 Community Members

Decimal to Binary Conversion Logic. Help!

Member Avatar
sadzee
Newbie Poster
5 posts since Mar 2012
Reputation Points: 0 [?]
Q&As Helped to Solve: 0 [?]
Skill Endorsements: 0 [?]
 
0
 

This is the Logic for converting a Decimal number to Binary.
I'm having confusion in getting it.
It would be great if someone make me understand this.

for ( long decimal = d ; decimal > 0 ; decimal/=2 )

      {

       binary = decimal%2 + binary  ;

      }

If d=4 then in fisrt go:
4/2=2 and 4%2=0
So, binary = decimal%2 + binary => binary = 0 + (what will be the value of binary here??)

Member Avatar
NormR1
Posting Sage
7,723 posts since Jun 2010
Reputation Points: 563 [?]
Q&As Helped to Solve: 793 [?]
Skill Endorsements: 16 [?]
Team Colleague
 
0
 

When trying to understand or debug code, use the println method to print out the values of all the expressions and variables being used it the code so you can see what the computer sees.

One confusion people have when talking about conversion is that everything in the computer is binary. An int value is made of 32 binary digits. The only way to see a "binary" or decimal representation for an int value is to format it into a String. You can not "see" the contents of an int. You can format the int to different Strings to display it in many different bases. The most common is base 10. But it can be formatted to any base.

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article