0

i wrote simple java code to convert from decimal to 8-bit binary: sorry for this stupid question

 1       int dec=1;
 2       String result="";
 3       String reverse = "";
 4       while(dec!=0)
 5           {
 6               result+=dec%2;
 7               dec=dec/2;    
 8           }            
 9       //8-Bit Binary 
 10       System.out.println("dec length is :"+result.length());

// int j=8-result.length(); // for(int i=0;i

 11        for(int i=0;i<(8-result.length());i++)
 12       {
 13            result+=0;
 14            System.out.println("*");
 15       }
 16       System.out.println("8-Bit before reverse:"+result); 
 17       for(int i = result.length() - 1; i >= 0; i--)
 18        {
 19           reverse = reverse + result.charAt(i);
 20        }
 21       System.out.println("8-bit representation:"+reverse);

the result was : dec length is :1 * * * * 8-Bit before reverse:10000 8-bit representation:00001

but when i remove line 13 (result+=0;) the compiler print 7 asterisk(*), what is the reason for that? length of result will update every time

3 Answers 3

1

It is because of the confition of your for loop:

for(int i=0;i<(8-result.length());i++)

And the action in it:

result+=0;

Increasing the length of result makes the result of 8-result.length() smaller (8 - 2 = 6, 8 - 3 = 5 ...), hence the loop being executed less times.

Sign up to request clarification or add additional context in comments.

Comments

0

Because result is a String. Adding an int zero to a String, like this

result+=0;

invokes the same behavior as

result+=String.valueOf(0);

1 Comment

@IhabKhaledShhadat it is not work!!!!!!!!!! Take a deep breath. The computer is a very fast idiot, doing exactly what it has been told to do. The fast way get a binary String is Integer.toBinaryString(int); beyond that, I cannot tell what your question is.
0
//Decimal to Binary Conversion
            int dec=1;
            String result= "00000000";
            int i=result.length()-1;
            while(dec!=0)
            {
              char a[]=result.toCharArray();
              a[i--]= String.valueOf(dec%2).charAt(0);
              result=new String(a);
              dec=dec/2;  

            }
            System.out.println(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.