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

Java中有没有内置函数?


当前回答

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

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

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

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

其他回答

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

由于没有答案被接受,也许您的问题是关于如何在二进制文件中存储整数。 dataoutputstream可能就是您要找的:https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

假设你指的是“内置”:

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

请参阅整型文档。

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

输入任何十进制数作为输入。在此之后,我们进行模运算和除法运算,将给定的输入转换为二进制数。 这是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());
    }
}