Converting decimal to binary in Java

前端 未结 9 2301
时光取名叫无心
时光取名叫无心 2020-12-03 15:18

I\'m trying to write a code that converts a number to binary, and this is what I wrote. It gives me couple of errors in Eclipse, which I don\'t understand. What\'s wrong wit

9条回答
  •  佛祖请我去吃肉
    2020-12-03 16:16

    There are a two main issues you need to address:

    • Don't declare a method inside another method.
    • Your loop will never end.

    For the first, people have already pointed out how to write that method. Note that normal method names in java are usually spelled with the first letter lowercase.

    For the second, you're never changing the value of int1, so you'll end up printing the LSB of the input in a tight loop. Try something like:

    do {
      System.out.println(int1 & 1);
      int1 = int1 >> 1;
    } while (int1 > 0);
    

    Explanation:

    • int1 & 1: that's a binary and. It "selects" the smallest bit (LSB), i.e. (a & 1) is one for odd numbers, zero for even numbers.
    • int1 >> 1: that's a right shift. It moves all the bits down one slot (>> 3 would move down 3 slots). LSB (bit 0) is discarded, bit 1 becomes LSB, bit 2 becomes bit one, etc... (a>>0) does nothing at all, leaves a intact.

    Then you'll notice that you're printing the digits in the "wrong order" - it's more natural to have them printed MSB to LSB. You're outputting in reverse. To fix that, you'll probably be better off with a for loop, checking each bit from MSB to LSB.

    The idea for the for loop would be to look at each of the 32 bits in the int, starting with the MSB so that they are printed left to right. Something like this

    for (i=31; i>=0; i--) {
      if (int1 & (1<

    1< is a left shift. Similar to the right shift, but in the other direction. (I haven't tested this at all.)

    Once you get that to work, I suggest as a further exercise that you try doing the same thing but do not print out the leading zeroes.

提交回复
热议问题