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

Java中有没有内置函数?


当前回答

这个问题在java中很棘手(可能在其他语言中也是如此)。

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

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

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

- 11110100110.

但它确实有效!!

其他回答

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

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());
System.out.println(Integer.toBinaryString(343));

给定int x的左填充零的二进制表示:

org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')
public static void main(String[] args) 
{
    int i = 13;
    short s = 13;
    byte b = 13;

    System.out.println("i: " + String.format("%32s", 
            Integer.toBinaryString(i)).replaceAll(" ", "0"));

    System.out.println("s: " + String.format("%16s", 
            Integer.toBinaryString(0xFFFF & s)).replaceAll(" ", "0"));

    System.out.println("b: " + String.format("%8s", 
            Integer.toBinaryString(0xFF & b)).replaceAll(" ", "0"));

}

输出:

i: 00000000000000000000000000001101
s: 0000000000001101
b: 00001101

试试这个方法:

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