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

Java中有没有内置函数?


当前回答

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

org.apache.commons.lang3.StringUtils.leftPad(Integer.toBinaryString(x), 32, '0')

其他回答

由于没有答案被接受,也许您的问题是关于如何在二进制文件中存储整数。 dataoutputstream可能就是您要找的:https://docs.oracle.com/javase/8/docs/api/java/io/DataOutputStream.html

DataOutputStream os = new DataOutputStream(outputStream);
os.writeInt(42);
os.flush();
os.close();

这里不需要只依赖二进制或任何其他格式…一个灵活的内置功能,打印任何格式,你想在你的程序..整数。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

这是我格式化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”

试试这个方法:

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

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

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