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

Java中有没有内置函数?


当前回答

这里不需要只依赖二进制或任何其他格式…一个灵活的内置功能,打印任何格式,你想在你的程序..整数。toString (int,表示)

Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation

其他回答

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

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

由于没有答案被接受,也许您的问题是关于如何在二进制文件中存储整数。 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的左填充零的二进制表示:

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

我认为这是迄今为止最简单的算法(对于那些不想使用内置函数的人来说):

public static String convertNumber(int a)  { 
              StringBuilder sb=new StringBuilder();
              sb.append(a & 1);
              while ((a>>=1) != 0)  { 
                  sb.append(a & 1);
               }
              sb.append("b0");
              return sb.reverse().toString();
  }

例子:

convertNumber(1)——> "0b1"

转换号(5)->“0b101”

转换号(117)->“0b1110101”

它的工作原理:while-loop将一个数字向右移动(将最后一位替换为倒数第二位,等等),获取最后一位的值并将其放入StringBuilder中,重复直到没有剩余的位(此时a=0)。