Print an integer in binary format in Java

2019-01-02 14:33发布

I have a number and I want to print it in binary. I don't want to do it by writing an algorithm, Is there any built-in function for that in Java?

标签: java
17条回答
查无此人
2楼-- · 2019-01-02 15:18

Old school:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));
查看更多
与君花间醉酒
3楼-- · 2019-01-02 15:19

The question is tricky in java (and probably also in other language).

A Integer is a 32-bit signed data type, but Integer.toBinaryString() returns a string representation of the integer argument as an unsigned integer in base 2.

So, Integer.parseInt(Integer.toBinaryString(X),2) can generate an exception (signed vs. unsigned).

The safe way is to use Integer.toString(X,2); this will generate something less elegant:

-11110100110

But it works!!!

查看更多
低头抚发
4楼-- · 2019-01-02 15:20

Enter any decimal number as an input. After that we operations like modulo and division to convert the given input into binary number. Here is the source code of the Java Program to Convert Integer Values into Binary and the bits number of this binary for his decimal number. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}
查看更多
浮光初槿花落
5楼-- · 2019-01-02 15:26
System.out.println(Integer.toBinaryString(343));
查看更多
旧人旧事旧时光
6楼-- · 2019-01-02 15:28

I think it's the simplest algorithm so far (for those who don't want to use built-in functions):

public static String convertNumber(int a)  { 
              StringBuilder sb=new StringBuilder();
              sb.append(a & 1);
              while ((a>>=1) != 0)  { 
                  sb.append(a & 1);
               }
              sb.append("b0");
              return sb.reverse().toString();
  }

Example:

convertNumber(1) --> "0b1"

convertNumber(5) --> "0b101"

convertNumber(117) --> "0b1110101"

How it works: while-loop moves a-number to the right (replacing the last bit with second-to-last, etc), gets the last bit's value and puts it in StringBuilder, repeats until there are no bits left (that's when a=0).

查看更多
登录 后发表回答