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

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

其他回答

我需要一些东西可以很好地打印出来,并把每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 void printBinaryNumbers(int n) {
        char[] arr = Integer.toBinaryString(n).toCharArray();
        StringBuilder sb = new StringBuilder();
        for (Character c : arr) {
          sb.append(c);
        }
        System.out.println(sb);
      }

输入

5

输出

101

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

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