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

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

其他回答

假设你指的是“内置”:

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

请参阅整型文档。

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

System.out.println(Integer.toBinaryString(343));

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

我需要一些东西可以很好地打印出来,并把每n位的比特分开。换句话说,显示前导零并显示如下内容:

n = 5463
output = 0000 0000 0000 0000 0001 0101 0101 0111

我是这么写的:

/**
 * Converts an integer to a 32-bit binary string
 * @param number
 *      The number to convert
 * @param groupSize
 *      The number of bits in a group
 * @return
 *      The 32-bit long bit string
 */
public static String intToString(int number, int groupSize) {
    StringBuilder result = new StringBuilder();

    for(int i = 31; i >= 0 ; i--) {
        int mask = 1 << i;
        result.append((number & mask) != 0 ? "1" : "0");

        if (i % groupSize == 0)
            result.append(" ");
    }
    result.replace(result.length() - 1, result.length(), "");

    return result.toString();
}

像这样调用它:

public static void main(String[] args) {
    System.out.println(intToString(5463, 4));
}

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

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