0
votes

What I'm trying to do is convert any number up to 2^32 - 1 that is input by the user to its binary value using only bitwise operators. After much head scratching and tinkering, I've come to this conclusion that seems to be giving me what I want... almost:

public static void main(String[] args) {

  Scanner scan = new Scanner(System.in);

  System.out.print("Enter a number: ");
  String input = scan.nextLine();

  int dec = Integer.parseInt(input);

  ArrayList<Integer> binary = new ArrayList<Integer>();

  for (int i = 0; i < 32; i++) {
     if ((dec & 1) == 0) {
        binary.add(0);
     } else {
        binary.add(1);
     }
     dec = dec >>> 1;
  }

  Object[] binaryArray = binary.toArray();

  for (int i = binaryArray.length - 1; i >= 0; i--) {
     System.out.print(binaryArray[i]);
  }

}

Here's my problem now: This does output the proper binary string, but I need to remove the leading zeros so that the decimal number 10 comes out as 1010 in binary rather than 00000000000000000000000000001010.

I'm a first semester CS student, so any help on solving the issue or tips on cleaning up the code would be greatly appreciated.

2
Hint: when you print a digit in binary, try removing that digit from the integer. What happens to the remaining number? - markspace
Edit: I see you actually are removing the digit by shifting it to the right. Now the only question is what happens to the variable dec when you do that enough times. - markspace
Further commentary: it's wrong to think of an integer like dec as "decimal." All numbers (and strings/letters) in a computer are actually stored in a binary format. What you're printing now is actually how the number is really formatted inside a computer. - markspace
The binary conversion is already done by Integer.parseInt(input);. Everything after it is a complete waste of time and space. - user207421
Assuming you are not handling negative integers, the range is 2^31-1. See also Integer.toBinaryString. - Andy

2 Answers

1
votes

Reading your code a third time, I noticed something that's a bit tricky. What you're doing is OK, but there might be a better way. I'm not going to give the answer, but I want to look at something different.

The ArrayList in your code is not needed. What if you wrote the code this way?

  for (int i = 1 << 31; i != 0; i = i >>> 1) {
     if ((dec & i) == 0) {
        System.out.print( "0" );  //binary.add(0);
     } else {
        System.out.print( "1" );  //binary.add(1);
     }
  }

Here I simply "print as I go." The ArrayList and the conversion to an array are unneeded. I've already got one loop working and I don't need to add a second loop to print all the values of the array, because I just use the loop I already have.

OK, so the first bit of code I had was wrong. It prints in the reverse order. This code (should! untested!) starts at bit #32 and count down from there, printing the bits in order. It also shows how you can use other things in a for loop, like i = i >>> 1 instead of just always doing ++.

Elaborating on the hint: A quick way to "see" what you code is doing is to print important values as your code runs. For example, to get an idea what you might do with dec, add a print statement to print its value. Some people say to use a debugger and step through code but I find print statements to be faster.

     for( int i = 0; i < 32 ; i++ ) {
        if( (dec & 1) == 0 ) {
           binary.add( 0 );
        } else {
           binary.add( 1 );
        }
        dec = dec >>> 1;
        System.out.println( "DEBUG: " + dec );
     }
0
votes

Based on my understanding from your question here is what i can Think of.

If you just want to remove leading zeros using your own approach here is the work around , However i would not recommend you to do that, its bulky and not readable.

  public static void main(String[] args) {

    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a number: ");
    String input = scan.nextLine();

    int dec = Integer.parseInt(input);
    ArrayList<Integer> binary = new ArrayList<>();
    for (int i = 0; i < 32; i++) {
        if ((dec & 1) == 0) {
            binary.add(0);
        } else {
            binary.add(1);
        }
        dec = dec >>> 1;
    }
    StringBuilder ss = new StringBuilder();
    for (int i = binary.size() - 1; i >= 0; i--) {
        ss.append(binary.get(i));
    }
    System.out.println(Integer.parseInt(ss.toString()));
  }

Or you can use this approach lesser codes :) easy to read

  public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    System.out.print("Enter a number: ");
    String input = scan.nextLine();
    int dec = Integer.parseInt(input);
    char[] arr = Integer.toBinaryString(dec).toCharArray();
    StringBuilder sb = new StringBuilder();
    for (Character c : arr) {
        sb.append(c);
    }
    System.out.println(sb);
  }