This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

How do I print integers in binary format in Java?

I have a number that I want to print in binary. I don’t want to write an algorithm.

Are there any built-in functions in Java?

Answer a

. There e is a flexible built-in function that can print any format you want in your program. Integer.tostring (int, notation);

Integer.toString(100.8) // prints 144 --octal representation

Integer.toString(100.2) // prints 1100100 --binary representation

Integer.toString(100.16) //prints 64 --Hex representation
Copy the code

Answer two

I need something to print well and separate every n bits. In other words, display the leading zero and display the following:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111
Copy the code

Here’s the algorithm I wrote

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1<< i; result.append((number & mask) ! =0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append("");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}
Copy the code

Call it like this:

public static void main(String[] args) {
    System.out.println(intToString(5463.4));
}
Copy the code

Answer three

Look at the logic that can convert a number to any base

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
        }
    }
    for (int j = binary.length() - 1; j >= 0; j--) { System.out.print(binary.charAt(j)); }}Copy the code

or

StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
    if((n&1) = =1){
        binary.append(1);
    }else
        binary.append(0);
    n>>=1;
}
System.out.println(binary.reverse());
Copy the code

The article translated from Stack Overflow:stackoverflow.com/questions/5…