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

Java中有没有内置函数?


当前回答

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

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

其他回答

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

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中很棘手(可能在其他语言中也是如此)。

Integer是32位有符号数据类型,但Integer. tobinarystring()返回整数参数的字符串表示形式,以2为基数的无符号整数。

因此,Integer.parseInt(Integer.toBinaryString(X),2)可以生成一个异常(有符号vs无符号)。

安全的方法是使用Integer.toString(X,2);这将生成一些不那么优雅的东西:

- 11110100110.

但它确实有效!!

您可以使用位掩码(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();
}

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

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

试试这个方法:

public class Bin {
  public static void main(String[] args) {
    System.out.println(toBinary(0x94, 8));
  }

  public static String toBinary(int a, int bits) {
    if (--bits > 0)
        return toBinary(a>>1, bits)+((a&0x1)==0?"0":"1");
    else 
        return (a&0x1)==0?"0":"1";
  }

}

10010100