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

Java中有没有内置函数?


当前回答

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

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());

其他回答

假设你指的是“内置”:

int x = 100;
System.out.println(Integer.toBinaryString(x));

请参阅整型文档。

(Long有一个类似的方法,BigInteger有一个实例方法,你可以在其中指定基数。)

简单又简单的解决方法。

public static String intToBinaryString(int integer, int numberOfBits) {

    if (numberOfBits > 0) {     // To prevent FormatFlagsConversionMismatchException.

        String nBits = String.format("%" + numberOfBits + "s",      // Int to bits conversion
                Integer.toBinaryString(integer))
                .replaceAll(" ","0"); 

        return nBits;   // returning the Bits for the given int.
    }

    return null;        // if the numberOfBits is not greater than 0, returning null.
}

tostring (value,numbersystem)——使用的语法 然后传递值

Integer.toString(100,8) //打印144—八进制

Integer.toString(100,2) //打印1100100—二进制

Integer.toString(100,16) //打印64—十六进制

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

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();
    }

输入任何十进制数作为输入。在此之后,我们进行模运算和除法运算,将给定的输入转换为二进制数。 这是Java程序的源代码,将整数值转换为二进制和他的十进制数的二进制位数。 Java程序编译成功并在Windows系统上运行。程序输出如下所示。

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int integer ;
        String binary = "";    //   here we count "" or null 
                               //   just String binary = null;
        System.out.print("Enter the binary Number: ");
        integer = sc.nextInt();

        while(integer>0)
        {
            int x = integer % 2;
            binary = x + binary;
            integer = integer / 2;  
        }
        System.out.println("Your binary number is : "+binary);
        System.out.println("your binary length : " + binary.length());
    }
}