我有一个数字,我想把它打印成二进制。我不想通过写算法来实现。

Java中有没有内置函数?


当前回答

“ 长k = 272214023L;

字符串长= String.format(64年代“%”,Long.toBinaryString (k)。替换(',' 0 ');

String long1 = String.format("%64s",Long.toBinaryString(k))。replace(' ','0').replaceAll("(\d{8})","$1 "); ` 打印: 0000000000000000000000000000000000000000000

00000000 00000000 00000000 00000000 00000000 0000000

其他回答

它使用强大的位操作处理有符号和无符号值,并生成左边的第一个零。

public static String representDigits(int num) {

        int checkBit = 1 << (Integer.SIZE * 8 - 2 );    // avoid the first digit        
        StringBuffer sb = new StringBuffer();

        if (num < 0 ) {     // checking the first digit
            sb.append("1");
        } else {
            sb.append("0");
        }

        while(checkBit != 0) {          
            if ((num & checkBit) == checkBit){
                sb.append("1");
            } else {
                sb.append("0");
            }           
            checkBit >>= 1;     
        }       

        return sb.toString();
    }
System.out.println(Integer.toBinaryString(343));

给定int x的左填充零的二进制表示:

org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')

看看这个逻辑可以把一个数字转换成任何进制

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
        }
    }
    for (int j = binary.length() - 1; j >= 0; j--) {
        System.out.print(binary.charAt(j));
    }
}

OR

StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
    if((n&1)==1){
        binary.append(1);
    }else
        binary.append(0);
    n>>=1;
}
System.out.println(binary.reverse());

您可以使用位掩码(1<< k)和与数字做与操作! 1 << k在k位有1位!

private void printBits(int x) {
    for(int i = 31; i >= 0; i--) {
        if((x & (1 << i)) != 0){
            System.out.print(1);
        }else {
            System.out.print(0);
        }
    }
    System.out.println();
}