在Java中将整数转换为二进制字符串表示?

207

在Java中,将int类型转换为二进制字符串的最佳方法(理想情况下最简单)是什么?

例如,如果要转换的int值为156,则其二进制字符串表示形式应为“10011100”。

19个回答

415
Integer.toBinaryString(int i)

6
@Jack,有没有一种方法可以获得固定位数的二进制字符串,比如将十进制8转换成8位二进制00001000? - Kasun Siyambalapitiya
@KasunSiyambalapitiya,你可以使用Apache Commons中的StringUtils.leftPad。 - Sebastian
或者你可以这样做来获取前导零: String.format("%8s", Integer.toBinaryString(i)).replace(' ', '0') - undefined

45

还有一个java.lang.Integer.toString(int i, int base)方法,如果您的代码将来可能处理二进制以外的其他进制,则此方法更适合。请注意,该方法仅为整数i提供无符号表示,如果i为负数,则在前面添加一个负号。它不会使用二进制补码。


32
public static string intToBinary(int n)
{
    String s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}

1
此代码无法处理负整数。 - Lesya

23

另一种方法-通过使用java.lang.Integer,您可以获取第一个参数i的字符串表示形式,该字符串表示形式由第二个参数指定的基数(八进制-8,十六进制-16,二进制-2)来确定。

 Integer.toString(i, radix)

例子_

private void getStrtingRadix() {
        // TODO Auto-generated method stub
         /* returns the string representation of the 
          unsigned integer in concern radix*/
         System.out.println("Binary eqivalent of 100 = " + Integer.toString(100, 2));
         System.out.println("Octal eqivalent of 100 = " + Integer.toString(100, 8));
         System.out.println("Decimal eqivalent of 100 = " + Integer.toString(100, 10));
         System.out.println("Hexadecimal eqivalent of 100 = " + Integer.toString(100, 16));
    }

输出_

Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64

5
public class Main  {

   public static String toBinary(int n, int l ) throws Exception {
       double pow =  Math.pow(2, l);
       StringBuilder binary = new StringBuilder();
        if ( pow < n ) {
            throw new Exception("The length must be big from number ");
        }
       int shift = l- 1;
       for (; shift >= 0 ; shift--) {
           int bit = (n >> shift) & 1;
           if (bit == 1) {
               binary.append("1");
           } else {
               binary.append("0");
           }
       }
       return binary.toString();
   }

    public static void main(String[] args) throws Exception {
        System.out.println(" binary = " + toBinary(7, 4));
        System.out.println(" binary = " + Integer.toString(7,2));
    }
}

结果 二进制 = 0111 二进制 = 111 - Artavazd Manukyan
1
字符串 hexString = String.format("%2s", Integer.toHexString(h)).replace(' ', '0'); - Artavazd Manukyan

5

将整数转换为二进制:

import java.util.Scanner;

public class IntegerToBinary {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter Integer: ");
        String integerString =input.nextLine();

        System.out.println("Binary Number: "+Integer.toBinaryString(Integer.parseInt(integerString)));
    }

}

输出:

输入整数:

10

二进制数:1010


1
过度宣传某个特定的产品/资源(我在这里删除了)可能会被社区视为垃圾邮件。请查看[帮助],特别是用户应该遵守哪些行为准则?的最后一节:_避免明显的自我推销_。您可能还对如何在Stack Overflow上进行广告宣传?感兴趣。 - Tunaki

5

最简单的方法是检查数字是否为奇数。如果是,根据定义,它的最右边的二进制数字将是“ 1”(2 ^ 0)。之后,我们将数字向右位移,并使用递归检查相同的值。

@Test
public void shouldPrintBinary() {
    StringBuilder sb = new StringBuilder();
    convert(1234, sb);
}

private void convert(int n, StringBuilder sb) {

    if (n > 0) {
        sb.append(n % 2);
        convert(n >> 1, sb);
    } else {
        System.out.println(sb.reverse().toString());
    }
}

1
我认为,如果你真的不想使用内置方法,这是一种非常优雅的手动完成它的方式。 - praneetloke

5

这是我几分钟前随便写的东西。希望能有所帮助!

public class Main {

public static void main(String[] args) {

    ArrayList<Integer> powers = new ArrayList<Integer>();
    ArrayList<Integer> binaryStore = new ArrayList<Integer>();

    powers.add(128);
    powers.add(64);
    powers.add(32);
    powers.add(16);
    powers.add(8);
    powers.add(4);
    powers.add(2);
    powers.add(1);

    Scanner sc = new Scanner(System.in);
    System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
    int input = sc.nextInt();
    int printableInput = input;

    for (int i : powers) {
        if (input < i) {
            binaryStore.add(0);     
        } else {
            input = input - i;
            binaryStore.add(1);             
        }           
    }

    String newString= binaryStore.toString();
    String finalOutput = newString.replace("[", "")
            .replace(" ", "")
            .replace("]", "")
            .replace(",", "");

    System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
    sc.close();
}   

}


4

使用内置函数:

String binaryNum = Integer.toBinaryString(int num);

如果你不想使用内置的将整数转换为二进制的函数,你也可以这样做:

import java.util.*;
public class IntToBinary {
    public static void main(String[] args) {
        Scanner d = new Scanner(System.in);
        int n;
        n = d.nextInt();
        StringBuilder sb = new StringBuilder();
        while(n > 0){
        int r = n%2;
        sb.append(r);
        n = n/2;
        }
        System.out.println(sb.reverse());        
    }
}

4

这是我的方法,它有一个固定字节数的小优点。

private void printByte(int value) {
String currentBinary = Integer.toBinaryString(256 + value);
System.out.println(currentBinary.substring(currentBinary.length() - 8));
}

public int binaryToInteger(String binary) {
char[] numbers = binary.toCharArray();
int result = 0;
for(int i=numbers.length - 1; i>=0; i--)
  if(numbers[i]=='1')
    result += Math.pow(2, (numbers.length-i - 1));
return result;
}

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