Instance of the toBinaryString of method of Integer in Java
- 2020-04-01 02:34:10
- OfStack
During an interview, I was asked to write out the toBinaryString() method in the Integer class
In other words, write out the process of converting an Integer to a Binary
But I was surprised, in the JDK source code, found this very useful method, here to show you
Here's a test I did:
package com.b510.test;
public class TestF {
public static void main(String[] args) {
//output:1000
System.out.println(toBinaryString(8));
//printInfo();
}
private static void printInfo(){
for(int i =0; i< 10; i++){
System.out.println("i= " + i + " "+(i & 1));
}
}
public static String toBinaryString(int i) {
return toUnsignedString(i, 1);
}
private static String toUnsignedString(int i, int shift) {
char[] buf = new char[32];
int charPos = 32;
int radix = 1 << shift;
int mask = radix - 1;
do {
//The mask is always 1, so when I is odd, the "I & mask" operation is 1
//Otherwise returns: 0
//System.out.println(i & mask);
buf[--charPos] = digits[i & mask];
i >>>= shift;//Shift the assignment to the right and fill the empty bit on the left with 0
//System.out.println(buf);
//System.out.println(charPos);
//System.out.println(i);
} while (i != 0);
return new String(buf, charPos, (32 - charPos));
}
final static char[] digits = {
'0' , '1' , '2' , '3' , '4' , '5' ,
'6' , '7' , '8' , '9' , 'a' , 'b' ,
'c' , 'd' , 'e' , 'f' , 'g' , 'h' ,
'i' , 'j' , 'k' , 'l' , 'm' , 'n' ,
'o' , 'p' , 'q' , 'r' , 's' , 't' ,
'u' , 'v' , 'w' , 'x' , 'y' , 'z'
};
}
In our code, we can actually simplify the digits array, because we'll only use the array: digits[0],digits[1]
So:
final static char[] digits = {
'0' , '1'
};
The method USES the shift and & operations, which are key.