Converting decimal to binary in Java

前端 未结 9 2289
时光取名叫无心
时光取名叫无心 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 15:55

    Maybe you don't want to use toBinaryString(). You said that you are learning at the moment, so you can do it yourself like this:

    /*
      F:\>java A 123
      123
        1  1  0  1  1  1  1  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0  0
      0  0  0  0  0  0
    */
    
    public class A {
        public static void main(String[] args) {
    
            int a = Integer.parseInt(args[0]);
            System.out.println(a);
    
            int bit=1;
            for(int i=0; i<32; i++) {
                System.out.print("  "+(((a&bit)==0)?0:1));
                bit*=2;
            }
        }
    }
    

提交回复
热议问题