-3

I'm trying to convert decimal to binary but some how when I convert 128 binary the output gives me 11111110, I tried to fix the calculation but still end up with the same output.

import java.lang.*;

public class HA7BinaryErr {
    public static void main(String[] argv) {
        Scanner input = new Scanner(System.in);
        int number = 0;
        int factorOfTwo = 0;
        // get number to convert from user
        do {
            System.out.println("Enter the number to convert (0-255): ");
            number = input.nextInt();

        } while (number < 0 || number > 255);
        System.out.println("The number " + number + " converted to binary is : ");
        // convert to binary by successively dividing by larger factors of 2
        for (factorOfTwo = 1; factorOfTwo <= 128; factorOfTwo *= 2) {
            if (number / factorOfTwo >= 1) {
                System.out.print("1");
                number -= factorOfTwo;
            } else
                System.out.print("0");
        }

    } // end of main
}// end of class
gonzo
  • 2,103
  • 1
  • 15
  • 27
Joe
  • 19
  • 2
  • What was the first value of `factorOfTwo` that it went wrong for? – Oliver Charlesworth Jul 27 '16 at 20:00
  • Please indent your code consistently if you are asking people to try and read it. – khelwood Jul 27 '16 at 20:02
  • 1
    Possible duplicate of [Converting Decimal to Binary Java](http://stackoverflow.com/questions/14784630/converting-decimal-to-binary-java) – UserF40 Jul 27 '16 at 20:04
  • One line: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int) you can see how this is implemented in Integer by going into the src.zip archive in the JDK and opening Integer.java – ControlAltDel Jul 27 '16 at 20:05
  • You're trying to convert *binary* to binary ASCII. `nextInt()` returns binary. `int` is binary. Everything is binary. – user207421 Aug 22 '17 at 04:24

3 Answers3

3

You have a problem that you are writing the number backwards. You need to start with the highest bit first

for (int powerOfTwo = 128; powerOfTwo > 0; powerOfTwo /= 2) {

When you are writing in decimal you start with the highest power e.g. 1234 is 1 * 1000 + 2 * 100 + 3 * 10 + 4 * 1

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You could take the easy way out and use: Integer.toBinaryString(int i) then print the string to the console. Check it out here.

Imposter
  • 253
  • 1
  • 10
-1
public class DCTB {


    public void convertor(int n)
    {
        for(int i=0;i<10;i++)
        {
        int arr=(int) (n%2);
        n=n/2;
        System.out.println(Integer.toString(arr));
        }   
    }

    public static void main(String args[])
    {
    DCTB obj=new DCTB();
    obj.convertor(10);
        }

}
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Pranjal Gupta
  • 581
  • 7
  • 10