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

发布于 2024-08-24 22:15:05 字数 103 浏览 7 评论 0原文

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

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

What would be the best way (ideally, simplest) to convert an int to a binary string representation in Java?

For example, say the int is 156. The binary string representation of this would be "10011100".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

酒解孤独 2024-08-31 22:15:06

使用内置函数:

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

Using built-in function:

String binaryNum = Integer.toBinaryString(int num);

If you don't want to use the built-in function for converting int to binary then you can also do this:

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());        
    }
}
羅雙樹 2024-08-31 22:15:06

这是我的方法,有点让人相信字节数是固定的

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

here is my methods, it is a little bit convince that number of bytes fixed

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;
}
握住我的手 2024-08-31 22:15:06

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

public static String convertDecimalToBinary(int N) {

    StringBuilder binary = new StringBuilder(32);

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

    return binary.reverse().toString();

}

Using bit shift is a little quicker...

public static String convertDecimalToBinary(int N) {

    StringBuilder binary = new StringBuilder(32);

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

    return binary.reverse().toString();

}
梦太阳 2024-08-31 22:15:06

如果int值为15,则可以将其转换为二进制,如下所示。

int x = 15;

Integer.toBinaryString(x);

如果您有二进制值,可以将其转换为 int 值,如下所示。

String binaryValue = "1010";

Integer.parseInt(binaryValue, 2);

if the int value is 15, you can convert it to a binary as follows.

int x = 15;

Integer.toBinaryString(x);

if you have the binary value, you can convert it into int value as follows.

String binaryValue = "1010";

Integer.parseInt(binaryValue, 2);
素罗衫 2024-08-31 22:15:06

这可以用伪代码表示为:

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

This can be expressed in pseudocode as:

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
老街孤人 2024-08-31 22:15:06

您确实应该使用 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);
}

You should really use Integer.toBinaryString() (as shown above), but if for some reason you want your own:

// 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);
}
怂人 2024-08-31 22:15:06

我的2分钱:

public class Integer2Binary {
    public static void main(String[] args) {
        final int integer12 = 12;
        System.out.println(integer12 + " -> " + integer2Binary(integer12));
        // 12 -> 00000000000000000000000000001100
    }

    private static String integer2Binary(int n) {
        return new StringBuilder(Integer.toBinaryString(n))
            .insert(0, "0".repeat(Integer.numberOfLeadingZeros(n)))
            .toString();
    }
}

My 2cents:

public class Integer2Binary {
    public static void main(String[] args) {
        final int integer12 = 12;
        System.out.println(integer12 + " -> " + integer2Binary(integer12));
        // 12 -> 00000000000000000000000000001100
    }

    private static String integer2Binary(int n) {
        return new StringBuilder(Integer.toBinaryString(n))
            .insert(0, "0".repeat(Integer.numberOfLeadingZeros(n)))
            .toString();
    }
}
深海少女心 2024-08-31 22:15:06

这应该很简单,如下所示:

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

}

This should be quite simple with something like this :

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

}
挥剑断情 2024-08-31 22:15:06
public class BinaryConverter {

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

            binary = binary + i;
            binaryConverter(number/2);
        }
        return binary;
    }
}
public class BinaryConverter {

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

            binary = binary + i;
            binaryConverter(number/2);
        }
        return binary;
    }
}
甩你一脸翔 2024-08-31 22:15:06

为了使其恰好是 8 位,我对 @sandeep-saini 的答案做了一些补充:

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

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

        return sb.reverse().toString();

    }

所以现在对于 1 的输入,你会得到 00000001 的输出

In order to make it exactly 8 bit, I made a slight addition to @sandeep-saini 's answer:

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

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

        return sb.reverse().toString();

    }

So now for an input of 1 you get an output of 00000001

苏大泽ㄣ 2024-08-31 22:15:06
public static String intToBinaryString(int n) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 32 && n != 0; i++) {
        sb.append((n&1) == 1 ? "1" : "0");
        n >>= 1;
    }
    return sb.reverse().toString();
}

我们不能使用n%2来检查第一位,因为它不适合负整数。我们应该使用n&1

public static String intToBinaryString(int n) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 32 && n != 0; i++) {
        sb.append((n&1) == 1 ? "1" : "0");
        n >>= 1;
    }
    return sb.reverse().toString();
}

We cannot use n%2 to check the first bit, because it's not right for negtive integer. We should use n&1.

雨的味道风的声音 2024-08-31 22:15:05
Integer.toBinaryString(int i)
Integer.toBinaryString(int i)
叫嚣ゝ 2024-08-31 22:15:05

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

There is also the java.lang.Integer.toString(int i, int base) method, which would be more appropriate if your code might one day handle bases other than 2 (binary). Keep in mind that this method only gives you an unsigned representation of the integer i, and if it is negative, it will tack on a negative sign at the front. It won't use two's complement.

笑看君怀她人 2024-08-31 22:15:05
public static string intToBinary(int n)
{
    String s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}
public static string intToBinary(int n)
{
    String s = "";
    while (n > 0)
    {
        s =  ( (n % 2 ) == 0 ? "0" : "1") +s;
        n = n / 2;
    }
    return s;
}
但可醉心 2024-08-31 22:15:05

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

 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

One more way- By using java.lang.Integer you can get string representation of the first argument i in the radix (Octal - 8, Hex - 16, Binary - 2) specified by the second argument.

 Integer.toString(i, radix)

Example_

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

OutPut_

Binary eqivalent of 100 = 1100100
Octal eqivalent of 100 = 144
Decimal eqivalent of 100 = 100
Hexadecimal eqivalent of 100 = 64
却一份温柔 2024-08-31 22:15:05
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));
    }
}
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));
    }
}
探春 2024-08-31 22:15:05

这是我几分钟前写的,只是胡乱写的。希望有帮助!

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

}

This is something I wrote a few minutes ago just messing around. Hope it helps!

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

}

墨小墨 2024-08-31 22:15:05

将整数转换为二进制:

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

Convert Integer to Binary:

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

}

Output:

Enter Integer:

10

Binary Number: 1010

说不完的你爱 2024-08-31 22:15:05

最简单的方法是检查数字是否为奇数。如果是,根据定义,其最右边的二进制数将为“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());
    }
}

The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.

@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());
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文