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

Java中有没有内置函数?


当前回答

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

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)。

其他回答

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

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

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

假设你指的是“内置”:

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

请参阅整型文档。

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

“ 长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