2

I've been trying to write a small and simple program that converts dec numbers to bin.The idea is that when the user enters a positive integer a for- cycle have to go through all the rounds of deviding the number /2 but it also have to get the tail (idk the math term really the actuall bin numbers) and write them in an array, thats the part Im having trouble with.I have predefined the array size of 30 (cant find a way to make a working array without specifying it's length) my idea was that then I could make a reversed array with length = index(i from the first for cycle) from the previous array with another for cycle etc. but when I tested the first array all I get is empty brackets printed: [] or nothing at all, eclipse doesnt find any errors in the code and I cant figure out whats wrong.I could use some help.Anyways here's the code:

    public static void decToBin(){


    int n;
    Scanner in = new Scanner(System.in);
    System.out.println("Enter a positive integer:");
    n = in.nextInt();
    in.close();

    if (n <= 0) {System.out.println("ERROR:n<=0");return;}
    else if (n > 0){

        int[] ostataci = new int[30];
        for (int i = 0;n <= 0;i++){

            ostataci[i] = n % 2;

            n = n / 2;
            // System.out.printf("%d %n", ostataci[i]); - even this one doesnt print at all
        }
    //  System.out.println(Arrays.toString(ostataci)); - nor this one


        }
    }   

Thanks for the replies Ive learnt a few new things.But since Im a newbie I wanted to do it with the metod I described thx for pointing me the error in the for cycle, that was my biggest problem, anyway heres the last code I wrote( working correctly) thats what I was trying to do from the beggining.

    public static void decToBin2(){
        int n;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a positive integer:");
        n = in.nextInt();
        in.close();
        int i = 0;
        int[] ostataci = new int[32];
        if (n <= 0) {System.out.println("ERROR:n<=0");return;}
        else if (n > 0){
        while (n > 0){
            i++;
            ostataci[i] = n % 2;
            n = n / 2;
         }
        }
    int reverse = i;
        int[] reversed = new int[reverse];
        for (int i2 = 0;i2 != reverse;i--,i2++){
         reversed[i2] = ostataci[i];
         System.out.print(reversed[i2]);
        }
}
  • Try ArrayList. And you may want to have a loot at this: http://stackoverflow.com/questions/14784630/converting-decimal-to-binary-java – borjab Feb 16 '15 at 10:45
  • 1
    That is a good algorithmic exercise. FYI, for production use, `Integer.toString(yourNumber, 2)` does the job. – Arnaud Denoyelle Feb 16 '15 at 10:59

6 Answers6

1

The immediate error is in the for loop:

  else if (n > 0) {
    // Since n > 0 it'll never run
    for (int i = 0;n <= 0;i++)

The implementation itself could be something like that (keep it simpler!):

...
if (n <= 0) 
  System.out.println("ERROR:n<=0");
else {
  // Why do we need array/ArrayList etc.? We are supposed to build a string!
  StringBuilder Sb = new StringBuilder();

  // while we have something to do... 
  // (are we supposed to compute exact number of steps? No)
  while (n > 0) {
    Sb.insert(0, n % 2);
    n /= 2;    
  }

  System.out.println(Sb.toString());
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

your for loop is wrong for (int i = 0;n <= 0;i++){ this just wont run change it to something like this while (n > 0) { and your code will works fine. also int is 32 bit so change int[] ostataci = new int[30]; to int[] ostataci = new int[32]; although it is better to uselist instead of array.

Lrrr
  • 4,755
  • 5
  • 41
  • 63
0

Your loop for (int i = 0;n <= 0;i++){ } won't execute because you know that n is positive (by your if condition), but the for condition demands that n be negative (n <= 0). I suspect you mean n>0 instead.

As for variable length arrays you can use Lists, although that might be better to add in later

rbennett485
  • 1,907
  • 15
  • 24
0

Decimals are already converted to binary on the computer, why don't you use bit wise operations to check the saved integer? Eg to check if bit n of an int is set, evaluate the boolean (number >> n) & 1. Just put that in a loop and you're done. Everyone else is making it too complicated.

texasflood
  • 1,571
  • 1
  • 13
  • 22
0

Here is an alternative approach, using the shift operator and bit-masking:

public static int[] dec2bin(int n) {
    int[] result = new int[32];
    for (int i = 0; i < 32; i++) {
        result[31-i] = n & 0x1;
        n >>= 1;
    }
    return result;
}

This will also work just fine for negative numbers.

Example usage:

public static void main(String[] args) {
    int[] result = dec2bin(5);
    for (int i : result)
        System.out.print(i);
    System.out.flush();
}

Ouput:

00000000000000000000000000000101

Explaination

The code n & 0x1 from above is bit-masking. The 0x1 is hex notation for the number 1. In binary, that number looks like this:

00000001

In the first iteration of the for loop, n looks like:

00000101

The & operator does a bit-by-bit (bitwise) comparison of the bits in the two numbers, 'anding' them together, producing a new number based on those comparisons. If either or both of the corresponding bits are 0, the resulting bit is 0. If both of them are 1, the resulting bit is 1. So, for the two numbers listed above, the result of 'anding' them together is:

00000001

Or, in decimal, 1. You'll note that that also happens to be the bit value of the rightmost bit in n. Which we save into the result array at the rightmost index.

Next, we shift (>>) n right by 1. This moves every bit along by one (the rightmost bit is lost), and the resulting n is now:

00000010

We repeat that process 32 times (for each of the 32 bits of an int) and at the end we get a result array containing the correct answer.

Jamie Cockburn
  • 7,379
  • 1
  • 24
  • 37
-1
Try this: 
package mypackage;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.util.Arrays;

public class Converter{

    final static int ARRAY_SIZE = 30;

    public static void main(String[] args){     
        int n;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a positive integer:");
        n = in.nextInt();
        in.close();

        if (n <= 0){
            System.out.println("ERROR:n<=0");
            return;
        }else if (n > 0){
            int[] ostataci = new int[ARRAY_SIZE];
            int i = 0;
            while (n>0){            
                ostataci[i] = n % 2;
                i++;
                n = n / 2;              
                System.out.printf("%d %n", ostataci[i]);
            }
        System.out.println("All done!");    
        System.out.println(Arrays.toString(ostataci));
        }
    }
}