-1

I can only get correct output for decimal less than five. the output for five is 110 when it should be 101. the output for six is 101 and the output for ten is 1100.

        //while loop divides each digit
   while (decimal > 0) 
   {

            //divides and digit becomes the remainder
        int digit = decimal % 2;

        //makes the digit into a string builder so it can be reversed  
        binaryresult.append(digit);

        decimal = decimal / 2;


        display.setText(binaryresult.reverse());
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    this post may help you http://stackoverflow.com/questions/5203974/converting-decimal-to-binary-in-java – Giru Bhai Jun 03 '14 at 10:11

4 Answers4

1

Usee the below code it may work for you

 import java.util.Scanner;

 public class decToBinary{

    public String decToBin(int n) {

      StringBuilder result = new StringBuilder();

      int i = 0;
      int b[] = new int[10];

         while (n != 0) {
            i++;
            b[i] = n % 2;
            n = n / 2;
         }

         for (int j = i; j > 0; j--) {
             result.append(b[j]);
          }
          return result.toString();
     }

    public static void main(String args[]){
       Scanner sc=new Scanner(System.in);
       System.out.println("Enter decimal no :");
       int n=sc.nextInt();
       System.out.println("binary numbers is :");
       decToBinary dtb = new decToBinary();
       System.out.println(dtb.decToBin(n));
       }
  }  
0

Something like this may be closer to what you are asking for:

    while (decimal > 0) {
        result.insert(0, (char) ((decimal % 2) + '0'));
        decimal /= 2;
    }

It uses insert to avoid reversing and adds the character instead of the number.

But you would be better off using a built in mechanism such as:

BigInteger.valueOf(decimal).toString(2)
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
0

i am not able to reproduce the behaviour using the following:

public static String decToBin(int n) {
    StringBuilder result = new StringBuilder();
    while (n > 0) {
        int dec = n % 2;
        result.append(dec);
        n = n / 2;
    }
    return result.reverse().toString();
}

however, consider using the build-in

public static String decToBin(int n) {
    return Integer.toBinaryString(n);
}

(or even BigInteger as stated above)

Zahlii
  • 818
  • 1
  • 7
  • 17
0

try this code , i hope this is what u r looking for:

public class DecimalToBinary {
    public static void main(String[] args)
    {
        int decimal=11;
        StringBuffer binaryValue=new StringBuffer();
        while(decimal>0 ){
            int rem=decimal%2;
            decimal=decimal/2;
            System.out.println("Remainder:"+rem);
            binaryValue.append(rem);
        }
        System.out.println("binary is:"+binaryValue.reverse());
    }
}
daniula
  • 6,898
  • 4
  • 32
  • 49