Answers for "How to display the Binary format of any number in java"

0

How to display the Binary format of any number in java

// By using the Java Integer.toBinaryString() method
Integer.toBinaryString(num);

// OR

// By manually creating your own method for it
public static String toBinary(int num) {
	StringBuilder binary = new StringBuilder();
	while (num > 0) {
    binary.append(n % 2);
		num /= 2;
	}
  	binary.reverse();
  	// return binary.toString(); (you could convert it to a string if you wanted)
}

// Alternatively;
public static void toBinary(int num){
     int[] binary = new int[40];
     int id = 0;
     while(num > 0){
       binary[id++] = num % 2;
       num /= 2;
     }
     for(int i = id-1; i >= 0; i--){
       System.out.print(binary[i]);
     }
}
Posted by: Guest on October-19-2021

Code answers related to "How to display the Binary format of any number in java"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language