There are multiple way to Convert an Integer into Binary.
Using Modulo and for loop method :-
- A binary number consists of only 0 and 1.
- First we Create and assign binary array size data.
- Take the number modulo by 2 and store the remainder into an array.
- Now convert an integer to binary divide the number by 2 until it becomes 0.
- Here we store the remainder into a binary array and pass this into for loop to iterate into reverse order.
- Print the binary array data.
Using toBinaryString() method :-
- Here use the Integer.toBinaryString() to convert integer to binary.
- This method accepts an argument in Int data-type and returns the binary string data.
Syntax :- public static String toBinaryString(int num)
public class ConvertDecimalToBinary {
//Using Modulo and for loop method :-
public void printBinaryData(int number){
System.out.println("Using Modulo and for loop method :-");
int binary[] = new int[25];
int index = 0;
while(number > 0){
binary[index++] = number%2;
number = number/2;
}
for(int i = index-1;i >= 0;i--){
System.out.print(binary[i]);
}
System.out.println();
}
public static void main(String a[]){
ConvertDecimalToBinary cdtb = new ConvertDecimalToBinary();
int value=57;
cdtb.printBinaryData(value);
// toBinaryString method
System.out.println("from toBinaryString method value :- " + Integer.toBinaryString(value));
}
}
Output :-
Using Modulo and for loop method :-
111001
from toBinaryString method value :- 111001