You can make your own toBinaryString method. But first you have to understand the << operator, it basically shifts binary numbers to the left by the value you give to it.
example:
int n = 1; // 0001
n = ( n<<(4-1) ); // shift the binary number of 1 to the left 3 times
System.out.println(toBinaryString(n)); // = 1000;
now you might ask what is the usage of this? well you can make your own toBinaryString method with the help of the shift operator to do what you want
but before jumping to the code you have to know how the & operator works:
1000 & 0001 = 0
public static String toBinaryString(int n) {
String binary = ""; //Start with an empty String
// int i in binary = 1000, as long as i > 0, divide by 2
for (int i = (1 << (4 - 1)); i > 0; i /= 2) {
// if binary n & i are NOT 0, add 1 to the String binary, Otherwise add 0
binary += (n & i) != 0 ? "1" : "0";
}
return binary;
}
let's say you put 1 as input:
toBinaryString(1); // 1 = 0001 in binary
the function starts:
i starts at a binary value of 1000 which is equal to int 8
is 8 bigger than 0? yes, divide by 2
8/2 = 4;
4 in binary is 00100, now lets compare it with our input 0001
00100 & 0001 = 0? // YES
add 0 to String binary.
now divide 4 by 2 and repeat the loop. The function will add 3 zeros and 1 at the end. That will be your 0001.
At the end of the loop binary will be your wanted value as a String.
I hope i helped
~Mostafa