将int转换为Java中的二进制字符串表示形式?


168

在Java中将int转换为二进制字符串表示形式的最佳方法(最好是最简单)是什么?

例如,假设int为156。其二进制字符串表示形式为“ 10011100”。

Answers:


329
Integer.toBinaryString(int i)

那很方便!有类似的做多方法吗?
泰勒对待

46
@ ttreat31:我并不是说这听起来很刻薄,但是在进行编程时,您确实应该随手准备好文档(在这种情况下为JavaDoc)。您不必问:长期以来,他们是否采用类似的方法?您需要查找它,而不是键入评论。
劳伦斯·多尔

5
@Jack有一种获取固定位数的二进制字符串的方法,例如8bit二进制中的十进制8,其中00001000
Kasun Siyambalapitiya



20

还有一个way-通过使用java.lang.Integer中,你可以得到的第一个参数的字符串表示iradix (Octal - 8, Hex - 16, Binary - 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
String hexString = String.format(“%2s”,Integer.toHexString(h))。replace('','0');
Artavazd Manukyan 2015年

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

}


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


对特定产品/资源的过度宣传(我在这里删除了)可能被社区视为垃圾邮件。特别看一下帮助中心用户应该有什么样的行为?的最后一部分:避免公开宣传。您可能也对我如何在堆栈溢出上做广告感兴趣
Tunaki

4

使用内置功能:

String binaryNum = Integer.toBinaryString(int num);

如果您不想使用内置函数将int转换为二进制,则也可以执行以下操作:

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

最简单的方法是检查数字是否为奇数。如果定义的话,它的最右边的二进制数将是“ 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 '18

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

3

使用位移会更快一点...

public static String convertDecimalToBinary(int N) {

    StringBuilder binary = new StringBuilder(32);

    while (N > 0 ) {
        binary.append( N % 2 );
        N >>= 1;
     }

    return binary.reverse().toString();

}

2

可以用伪代码表示为:

while(n > 0):
    remainder = n%2;
    n = n/2;
    Insert remainder to front of a list or push onto a stack

Print list or stack

1

您应该真正使用Integer.toBinaryString()(如上所示),但是如果出于某些原因您想要自己的:

// Like Integer.toBinaryString, but always returns 32 chars
public static String asBitString(int value) {
  final char[] buf = new char[32];
  for (int i = 31; i >= 0; i--) {
    buf[31 - i] = ((1 << i) & value) == 0 ? '0' : '1';
  }
  return new String(buf);
}

0

像这样的东西应该很简单:

public static String toBinary(int number){
    StringBuilder sb = new StringBuilder();

    if(number == 0)
        return "0";
    while(number>=1){
        sb.append(number%2);
        number = number / 2;
    }

    return sb.reverse().toString();

}

0

您还可以使用while循环将int转换为二进制。像这样,

import java.util.Scanner;

public class IntegerToBinary
{
   public static void main(String[] args)
   {
      int num;
      String str = "";
      Scanner sc = new Scanner(System.in);
      System.out.print("Please enter the a number : ");
      num = sc.nextInt();
      while(num > 0)
      {
         int y = num % 2;
         str = y + str;
         num = num / 2;
      }
      System.out.println("The binary conversion is : " + str);
      sc.close();
   }
}

源和参考- 在Java示例中将int转换为二进制


0
public class BinaryConverter {

    public static String binaryConverter(int number) {
        String binary = "";
        if (number == 1){
            binary = "1";
            System.out.print(binary);
            return binary;
        }
        if (number == 0){
            binary = "0";
            System.out.print(binary);
            return binary;
        }
        if (number > 1) {
            String i = Integer.toString(number % 2);

            binary = binary + i;
            binaryConverter(number/2);
        }
        System.out.print(binary);
        return binary;
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.