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

Java中有没有内置函数?


当前回答

这是我格式化Integer输出的方式。toBinaryString方法:

public String toBinaryString(int number, int groupSize) {
    String binary = Integer.toBinaryString(number);

    StringBuilder result = new StringBuilder(binary);
    for (int i = 1; i < binary.length(); i++) {
        if (i % groupSize == 0) {
            result.insert(binary.length() - i, " ");
        }
    }
    return result.toString();
}

toBinaryString(0xABFABF, 8)的结果是“10101011 11111010 10111111” 对于toBinaryString(0xABFABF, 4)是“1010 1011 1111 1010 1011 1111”

其他回答

    for(int i = 1; i <= 256; i++)
    {
        System.out.print(i + " "); //show integer
        System.out.println(Integer.toBinaryString(i) + " "); //show binary
        System.out.print(Integer.toOctalString(i) + " "); //show octal
        System.out.print(Integer.toHexString(i) + " "); //show hex

    }

看看这个逻辑可以把一个数字转换成任何进制

public static void toBase(int number, int base) {
    String binary = "";
    int temp = number/2+1;
    for (int j = 0; j < temp ; j++) {
        try {
            binary += "" + number % base;

            number /= base;
        } catch (Exception e) {
        }
    }
    for (int j = binary.length() - 1; j >= 0; j--) {
        System.out.print(binary.charAt(j));
    }
}

OR

StringBuilder binary = new StringBuilder();
int n=15;
while (n>0) {
    if((n&1)==1){
        binary.append(1);
    }else
        binary.append(0);
    n>>=1;
}
System.out.println(binary.reverse());

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

古老的学校:

    int value = 28;
    for(int i = 1, j = 0; i < 256; i = i << 1, j++)
        System.out.println(j + " " + ((value & i) > 0 ? 1 : 0));

输出(最低有效位在0位置):

0 0
1 0
2 1
3 1
4 1
5 0
6 0
7 0

我需要一些东西可以很好地打印出来,并把每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));
}