在Java中以二进制格式打印整数

321

我有一个数字,想要将它以二进制形式打印出来。我不想通过编写算法来实现。

在Java中是否有内置函数可以实现这个功能?


1
在这里提到的Integer.toBinaryString(i),将整数i转换为二进制字符串。 - lingar
25个回答

489

假设你的意思是“内置的”:

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

请查看Integer文档。(Long具有类似的方法,BigInteger具有一个实例方法,您可以在其中指定基数。)


4
这里省略了前导的零。 - Abu Ruqaiyah
1
@AbuRuqaiyah:OP从未提到前导零,而且我们需要知道他们期望有多少个... - Jon Skeet
如果您想要前导零,可以使用System.out.printf()来获得更多的控制。 - NomadMaker

268

在这里,不需要仅依赖于二进制或其他任何格式...一个灵活的内置函数可用,它可以打印您在程序中想要的任何格式。 Integer.toString(int, representation)

Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation

用不同的数字进行测试,包括负数、正数、大数、小数。 - Tertium
16
toBinaryString 方法输出二进制补码形式,toString 方法将数字转换为指定进制并在前面加上负号,因此 toString(-8, 2) 的结果为 "-1000"。请注意,这里的负号是在转换后添加的。 - Joe
同意,令人惊讶的是 Integer.toString(,,) 仍然是错误的!Formatter 对于 %x 和 %X 使用 Long.toBinaryString()。令人烦恼的是,除非你从 Integer/Long 中提取代码并进行适当调整,否则无法直接将内容附加到 StringBuilder 上;这并不难。 - Infernoz

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

24
我需要一些东西能够漂亮地打印出数据并且每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));
}

为什么需要result.replace(result.length() - 1, result.length(), "");?因为我们传递的是已经是32位的int。在倒数第二行我们要替换什么? - Parth
2
@Parth 在每一步中,我们都会将一个空格字符(“ ”)附加到字符串的末尾。你提到的那行代码将删除最后附加的空格字符。本质上,你可以调用String类的trim函数来实现相同的效果。 - Maghoumi
你可以通过将0x100000000加到该数字上,将其转换为长整型,然后舍弃前导1来更简单、高效地完成此操作。 - user207421
1
另一种选择是在条件中添加额外的检查:if (i%groupSize == 0 && i!= 0) - Ilya Serbis
Integer.toUnsignedLong()看起来是正确的答案,但似乎并没有给出正确的答案。Formatter使用以下逻辑: long v = value; if (value < 0) v += (1L << 32); - Infernoz

11
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

令人惊讶的是,Formatter没有提供布尔格式转换!当我将Formatter代码优化为单独的、优化的、编译形式时,我发现这一点。预编译后执行时间只需要1/5到1/3;鉴于printf样式的格式化非常有用,Sun和Oracle为什么不这样做也令人惊讶! - Infernoz

7

老派的做法:

    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

1
刚刚意识到我在答案后评论了3年...哈哈。 - rajugaadu

7

这是打印整数内部二进制表示最简单的方法。 例如:如果我们取n为17,则输出将为:0000 0000 0000 0000 0000 0000 0001 0001

void bitPattern(int n) {

        int mask = 1 << 31;
        int count = 0;
        while(mask != 0) {
            if(count%4 == 0)
                System.out.print(" ");

            if((mask&n) == 0) 

                System.out.print("0");



            else 
                System.out.print("1");


            count++;
            mask = mask >>> 1;


    }
    System.out.println();
}

6

看看这个逻辑,它可以将一个数字转换为任何进制。

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

或者

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

1
对于输入为0的情况,我们需要在上面第二个解决方案的while循环中添加以下代码行:if(a==0){ binary.append(0); System.out.println(binary.toString()); return; } - Imran

3

简单易行,非常简单的解决方案。

public static String intToBinaryString(int integer, int numberOfBits) {

    if (numberOfBits > 0) {     // To prevent FormatFlagsConversionMismatchException.

        String nBits = String.format("%" + numberOfBits + "s",      // Int to bits conversion
                Integer.toBinaryString(integer))
                .replaceAll(" ","0"); 

        return nBits;   // returning the Bits for the given int.
    }

    return null;        // if the numberOfBits is not greater than 0, returning null.
}

2
我能理解转换的过程,但请不要使用 return null。请使用守卫语句抛出 IllegalArgumentException 异常。在任何错误情况下返回 null 都是一种糟糕的构造方式,只会将问题推给调用者。 - Maarten Bodewes

2

只需尝试一下。如果范围仅限于打印给定整数值的二进制值。它可以是正数或负数。

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

input

5

Output

101


3
šłļšĽÄšĻąŤ¶Āťá挼ļtoBinaryStringŤŅĒŚõěÁöĄŚ≠óÁ¨¶šł≤Ôľü - OneCricketeer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接