我们在看java源码的时候,经常能看到通过位操作构造的常量。为了更好理解源码,我会把这些值打印出来(人肉运算估结果的旁友请忽略)。这个时候就需要用到这个方法了。java的Integer类是自带int转二进制字符串的,但是这个方法转换出来的二进制字符串只会保留最高非零位以后的字符串,不满32位。因此我再给他补个0就行。非常简单,自己做个记录,也方便他人。
根据自己需要传入位数。
//i 期望转换的整数 bitNum 期望转换的二进制字符串位数
public class IntToBinary32Utils {
public static String intToBinary32(int i, int bitNum){
String binaryStr = Integer.toBinaryString(i);
while(binaryStr.length() < bitNum){
binaryStr = "0"+binaryStr;
}
return binaryStr;
}
}
测试:
public class WhtTest {
private static final int COUNT_BITS = Integer.SIZE - 3;
private static final int RUNNING = -1 << COUNT_BITS;//111
private static final int SHUTDOWN = 0 << COUNT_BITS;//000
private static final int STOP = 1 << COUNT_BITS;//001
private static final int TIDYING = 2 << COUNT_BITS;//010
private static final int TERMINATED = 3 << COUNT_BITS;//011
private static final int CAPACITY = (1 << COUNT_BITS) - 1;
public static void main(String[] args){
System.out.println("RUNNING :"+IntToBinary32Utils.intToBinary32(RUNNING,32));
System.out.println("SHUTDOWN :"+IntToBinary32Utils.intToBinary32(SHUTDOWN,32));
System.out.println("STOP :"+IntToBinary32Utils.intToBinary32(STOP,32));
System.out.println("TIDYING :"+IntToBinary32Utils.intToBinary32(TIDYING,32));
System.out.println("TERMINATED:"+IntToBinary32Utils.intToBinary32(TERMINATED,32));
System.out.println("CAPACITY :"+IntToBinary32Utils.intToBinary32(CAPACITY,32));
}
}
输出: