33

我正在尝试使用 Java 将用户输入的十进制数转换为二进制数。

我收到错误。

package reversedBinary;
import java.util.Scanner;

public class ReversedBinary {


public static void main(String[] args) {
    int number; 

    Scanner in = new Scanner(System.in);

    System.out.println("Enter a positive integer");
    number=in.nextInt();

    if (number <0)
        System.out.println("Error: Not a positive integer");
    else { 

        System.out.print("Convert to binary is:");
        System.out.print(binaryform(number));
}

}

private static Object binaryform(int number) {
    int remainder;

    if (number <=1) {
        System.out.print(number);

    }

    remainder= number %2; 
    binaryform(number >>1);
    System.out.print(remainder);

    { 
    return null;
} } }

如何在 Java 中将十进制转换为二进制?

4

28 回答 28

85

Integer.toBinaryString()是一种内置方法,效果会很好。

于 2013-06-24T20:57:14.907 回答
42
Integer.toString(n,8) // decimal to octal

Integer.toString(n,2) // decimal to binary

Integer.toString(n,16) //decimal to Hex

其中 n = 十进制数。

于 2014-10-11T06:16:39.093 回答
14

您的binaryForm方法陷入无限递归,您需要返回 if number <= 1

import java.util.Scanner;

public class ReversedBinary {

    public static void main(String[] args) {
        int number;

        Scanner in = new Scanner(System.in);

        System.out.println("Enter a positive integer");
        number = in.nextInt();

        if (number < 0) {
            System.out.println("Error: Not a positive integer");
        } else {

            System.out.print("Convert to binary is:");
            //System.out.print(binaryform(number));
            printBinaryform(number);
        }
    }

    private static void printBinaryform(int number) {
        int remainder;

        if (number <= 1) {
            System.out.print(number);
            return; // KICK OUT OF THE RECURSION
        }

        remainder = number % 2;
        printBinaryform(number >> 1);
        System.out.print(remainder);
    }
}
于 2013-02-09T03:39:07.197 回答
6

我只想为使用以下内容的任何人添加:

   String x=Integer.toBinaryString()

获取二进制数字字符串并希望将该字符串转换为 int。如果你使用

  int y=Integer.parseInt(x)

你会得到一个 NumberFormatException 错误。

我将 String x 转换为 Integers 所做的工作是首先将 String x 中的每个单独的 Char 转换为 for 循环中的单个 Char。

  char t = (x.charAt(z));

然后我将每个 Char 转换回一个单独的字符串,

  String u=String.valueOf(t);

然后将每个字符串解析为一个整数。

Id figure Id post this,因为我花了一段时间才弄清楚如何将二进制(例如 01010101)转换为整数形式。

于 2014-09-17T00:34:32.183 回答
4
/**
 * @param no
 *            : Decimal no
 * @return binary as integer array
 */
public int[] convertBinary(int no) {
    int i = 0, temp[] = new int[7];
    int binary[];
    while (no > 0) {
        temp[i++] = no % 2;
        no /= 2;
    }
    binary = new int[i];
    int k = 0;
    for (int j = i - 1; j >= 0; j--) {
        binary[k++] = temp[j];
    }

    return binary;
}
于 2014-05-07T12:34:49.773 回答
3
public static void main(String h[])
{
    Scanner sc=new Scanner(System.in);
    int decimal=sc.nextInt();

    String binary="";

    if(decimal<=0)
    {
        System.out.println("Please Enter more than 0");

    }
    else
    {
        while(decimal>0)
        {

            binary=(decimal%2)+binary;
            decimal=decimal/2;

        }
        System.out.println("binary is:"+binary);

    }

}
于 2017-06-20T13:51:25.480 回答
1

以下将十进制转换为具有时间复杂度的二进制:O(n) 线性时间并且没有任何 java 内置函数

private static int decimalToBinary(int N) {
    StringBuilder builder = new StringBuilder();
    int base = 2;
    while (N != 0) {
        int reminder = N % base;
        builder.append(reminder);
        N = N / base;
    }

    return Integer.parseInt(builder.reverse().toString());
}
于 2018-05-17T16:36:55.130 回答
0

如果要反转计算的二进制形式,可以使用 StringBuffer 类并简单地使用 reverse() 方法。这是一个示例程序,将解释其用途并计算二进制

public class Binary {

    public StringBuffer calculateBinary(int number) {
        StringBuffer sBuf = new StringBuffer();
        int temp = 0;
        while (number > 0) {
            temp = number % 2;
            sBuf.append(temp);
            number = number / 2;
        }
        return sBuf.reverse();
    }
}


public class Main {

    public static void main(String[] args) throws IOException {
        System.out.println("enter the number you want to convert");
        BufferedReader bReader = new BufferedReader(newInputStreamReader(System.in));
        int number = Integer.parseInt(bReader.readLine());

        Binary binaryObject = new Binary();
        StringBuffer result = binaryObject.calculateBinary(number);
        System.out.println(result);
    }
}
于 2013-07-09T10:02:07.010 回答
0

这可能看起来很傻,但如果你想试试效用函数

System.out.println(Integer.parseInt((Integer.toString(i,2))));

必须有一些实用方法可以直接完成,我不记得了。

于 2013-12-20T16:13:45.343 回答
0

在 C# 中,但它与在 Java 中相同:

public static void findOnes2(int num)
{
    int count = 0;      // count 1's 
    String snum = "";   // final binary representation
    int rem = 0;        // remainder

    while (num != 0)
    {
        rem = num % 2;           // grab remainder
        snum += rem.ToString();  // build the binary rep
        num = num / 2;
        if (rem == 1)            // check if we have a 1 
            count++;             // if so add 1 to the count
    }

    char[] arr = snum.ToCharArray();
    Array.Reverse(arr);
    String snum2 = new string(arr);
    Console.WriteLine("Reporting ...");
    Console.WriteLine("The binary representation :" + snum2);
    Console.WriteLine("The number of 1's is :" + count);
}

public static void Main()
{
    findOnes2(10);
}
于 2014-02-19T00:34:38.800 回答
0
public static void main(String[] args)
{
    Scanner in =new Scanner(System.in);
    System.out.print("Put a number : ");
    int a=in.nextInt();
    StringBuffer b=new StringBuffer();
    while(a>=1)
    {
      if(a%2!=0)
      {
        b.append(1);
       }
      else if(a%2==0)
      {
         b.append(0);
      }
      a /=2;
    }
    System.out.println(b.reverse());
}
于 2015-03-19T00:17:16.297 回答
0

你所有的问题都可以用一条线来解决!要将我的解决方案合并到您的项目中,只需删除您的binaryform(int number)方法,然后替换System.out.print(binaryform(number));System.out.println(Integer.toBinaryString(number));.

于 2015-12-12T03:48:20.767 回答
0

不使用 Integer.ParseInt() 的二进制到十进制:

import java.util.Scanner;

//convert binary to decimal number in java without using Integer.parseInt() method.

public class BinaryToDecimalWithOutParseInt {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );
        System.out.println("Enter a binary number: ");

        int  binarynum =input.nextInt();
        int binary=binarynum;

        int decimal = 0;
        int power = 0;

        while(true){

            if(binary == 0){

                break;

            } else {

                int temp = binary%10;
                decimal += temp*Math.pow(2, power);
                binary = binary/10;
                power++;

            }
        }
        System.out.println("Binary="+binarynum+" Decimal="+decimal); ;
    }

}

输出:

输入一个二进制数:

1010

二进制=1010 十进制=10


使用 Integer.parseInt() 将二进制转换为十进制:

import java.util.Scanner;

//convert binary to decimal number in java using Integer.parseInt() method.
public class BinaryToDecimalWithParseInt {

    public static void main(String[] args) {

        Scanner input = new Scanner( System.in );

        System.out.println("Enter a binary number: ");
        String binaryString =input.nextLine();

        System.out.println("Result: "+Integer.parseInt(binaryString,2));

    }

}

输出:

输入一个二进制数:

1010

结果:10

于 2016-05-25T11:30:54.653 回答
0

一个相当简单而不是高效的程序,但它可以完成工作。

        Scanner sc = new Scanner(System.in);
        System.out.println("Give me my binaries");
        int str = sc.nextInt(2);
        System.out.println(str);
于 2018-04-17T12:24:33.817 回答
0
public static String convertToBinary(int dec)
{
    String str = "";
    while(dec!=0)
    {
        str += Integer.toString(dec%2);
        dec /= 2;
    }
    return new StringBuffer(str).reverse().toString();
}
于 2019-03-25T08:48:19.720 回答
0
/**
 * converting decimal to binary
 *
 * @param n the number
 */
private static void toBinary(int n) {
    if (n == 0) {
        return; //end of recursion
    } else {
        toBinary(n / 2);
        System.out.print(n % 2);
    }
}

/**
 * converting decimal to binary string
 *
 * @param n the number
 * @return the binary string of n
 */
private static String toBinaryString(int n) {
    Stack<Integer> bits = new Stack<>();
    do {
        bits.push(n % 2);
        n /= 2;
    } while (n != 0);

    StringBuilder builder = new StringBuilder();
    while (!bits.isEmpty()) {
        builder.append(bits.pop());
    }
    return builder.toString();
}

或者你可以使用Integer.toString(int i, int radix)

例如:(将 12 转换为二进制)

Integer.toString(12, 2)
于 2019-08-19T09:46:38.843 回答
0

实际上,您可以将其编写为递归函数。每个函数调用都返回它们的结果并添加到前一个结果的尾部。可以使用 java 编写此方法,如下所示:

public class Solution {

    private static String convertDecimalToBinary(int n) {
        String output = "";
        if (n >= 1) {
            output = convertDecimalToBinary(n >> 1) + (n % 2);
        }

        return output;
    }

    public static void main(String[] args) {
        int num = 125;
        String binaryStr = convertDecimalToBinary(num);

        System.out.println(binaryStr);
    }

}

让我们看看上面的递归是如何工作的:

在此处输入图像描述

调用一次 convertDecimalToBinary 方法后,它会调用自己,直到数字的值小于 1 并将所有连接的结果返回到它第一次调用的地方。

参考:

Java - 位和位移运算符https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html

于 2021-01-22T12:27:56.297 回答
0

更好的方法:

public static void main(String [] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(bf.readLine().trim());
        double ans = 0;
        int i=0;

        while(t!=0){
           int digit = t & 1;
           ans = ans + (digit*Math.pow(10,i));
           i++;
           t =t>>1;
        }
        System.out.println((int)ans);
    }
于 2022-01-14T12:59:17.903 回答
-1

我自己解决了这个问题,我想分享我的答案,因为它包括二进制反转然后转换为十进制。我不是一个非常有经验的编码器,但希望这对其他人有帮助。

我所做的是在转换二进制数据时将其推送到堆栈中,然后将其弹出以反转它并将其转换回十进制。

import java.util.Scanner;
import java.util.Stack;

public class ReversedBinary 
{
    private Stack<Integer> st;

    public ReversedBinary()
    {
        st = new Stack<>();
    }

    private int decimaltoBinary(int dec)
    {
        if(dec == 0 || dec == 1)
        {
            st.push(dec % 2);
            return dec;
        }

        st.push(dec % 2);

        dec = decimaltoBinary(dec / 2);        

        return dec;
    }

    private int reversedtoDecimal()
    {
        int revDec = st.pop();
        int i = 1;

        while(!st.isEmpty())
        {
            revDec += st.pop() * Math.pow(2, i++);
        }

        return revDec;
    }

    public static void main(String[] args)
    {
        ReversedBinary rev = new ReversedBinary();

        System.out.println("Please enter a positive integer:");

        Scanner sc = new Scanner(System.in);
        while(sc.hasNextLine())
        {
            int input = Integer.parseInt(sc.nextLine());
            if(input < 1 || input > 1000000000)
            {
                System.out.println("Integer must be between 1 and 1000000000!");
            }
            else
            {
                rev.decimaltoBinary(input);
                System.out.println("Binary to reversed, converted to decimal: " + rev.reversedtoDecimal());
            }
        }

    }
}
于 2015-04-23T22:37:50.080 回答
-1
import java.util.*;

public class BinaryNumber 
{
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number");
        int n = scan.nextInt();
        int rem;
        int num =n; 
        String str="";
        while(num>0)
        {
            rem = num%2;
            str = rem + str;
            num=num/2;
        }
        System.out.println("the bunary number for "+n+" is : "+str);
    }
}
于 2015-07-14T14:04:08.920 回答
-1

这是一个非常基本的程序,我在纸上写了一个一般程序后得到了这个。

import java.util.Scanner;

    public class DecimalToBinary {

        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            System.out.println("Enter a Number:");
            int number = input.nextInt();
            while(number!=0)
            {
                if(number%2==0) 
                {
                    number/=2;
                    System.out.print(0);//Example: 10/2 = 5     -> 0
                }
                else if(number%2==1) 
                {
                    number/=2;
                    System.out.print(1);// 5/2 = 2              -> 1
                }
                else if(number==2)
                {
                    number/=2;
                    System.out.print(01);// 2/2 = 0             -> 01   ->0101
                }
            }
        }
    }
于 2015-08-15T13:10:37.120 回答
-1
//converts decimal to binary string
String convertToBinary(int decimalNumber){  
    String binary="";
    while(decimalNumber>0){
        int remainder=decimalNumber%2;
        //line below ensures the remainders are reversed
        binary=remainder+binary;
        decimalNumber=decimalNumber/2;
    }
    return binary;

}
于 2016-06-01T00:00:10.633 回答
-1

最快的解决方案之一:

public static long getBinary(int n)
    {
        long res=0;
        int t=0;
        while(n>1)
        {
            t= (int) (Math.log(n)/Math.log(2));
            res = res+(long)(Math.pow(10, t));
            n-=Math.pow(2, t);
        }
        return res;
    }
于 2017-01-26T16:29:05.963 回答
-1

使用 StringBuilder 在正在构建的十进制字符串前面使用 insert() 效果更好,无需调用 reverse(),

static String toBinary(int n) {
    if (n == 0) {
        return "0";
    }

    StringBuilder bldr = new StringBuilder();
    while (n > 0) {
        bldr = bldr.insert(0, n % 2);
        n = n / 2;
    }

    return bldr.toString();
}
于 2017-11-02T22:54:02.527 回答
-1

好吧,你可以像这样使用while循环,

import java.util.*;
public class DecimalToBinaryDemo
{
    // this function converts decimal to binary
    static void toBinary(int num)
    {
       // here we are storing binary number
       int binaryNumber[] = new int[1000];
       // "count" variable is counter for binary array
       int count = 0;
       while(num > 0)
       {
          // storing remainder in binary array
          binaryNumber[count] = num % 2;
          num = num / 2;
          count++;
       }
       // here we are printing binary in reverse order
       for(int a = count - 1; a >= 0; a--)
          System.out.print(binaryNumber[a]);
    }
    public static void main(String[] args)
    {
       int number = 20;
       toBinary(number);
   }
}

输出: 10100

于 2017-11-18T12:48:37.067 回答
-2

不需要任何 java 内置函数。简单的递归就可以了。

public class DecimaltoBinaryTest {
     public static void main(String[] args) {
        DecimaltoBinary decimaltoBinary = new DecimaltoBinary();
        System.out.println("hello " + decimaltoBinary.convertToBinary(1000,0));
    }

}

class DecimaltoBinary {

    public DecimaltoBinary() {
    }

    public int convertToBinary(int num,int binary) {
        if (num == 0 || num == 1) {
            return num;
        } 
        binary = convertToBinary(num / 2, binary);
        binary = binary * 10 + (num % 2);
        return binary;
    }
}
于 2015-04-03T03:32:27.710 回答
-2

这是十进制到二进制的三种不同方式的转换

import java.util.Scanner;
public static Scanner scan = new Scanner(System.in);

    public static void conversionLogical(int ip){           ////////////My Method One 
        String str="";
        do{
            str=ip%2+str;
            ip=ip/2;

        }while(ip!=1);
        System.out.print(1+str);

    }
    public static void byMethod(int ip){                /////////////Online Method
        //Integer ii=new Integer(ip);
        System.out.print(Integer.toBinaryString(ip));
    }
    public static String recursion(int ip){             ////////////Using My Recursion

        if(ip==1)
            return "1";
        return (DecToBin.recursion(ip/2)+(ip%2));


    }

    public static void main(String[] args) {            ///Main Method

        int ip;         
        System.out.println("Enter Positive Integer");
        ip = scan.nextInt();

        System.out.print("\nResult 1 = ");  
        DecToBin.conversionLogical(ip);
        System.out.print("\nResult 2 = ");
        DecToBin.byMethod(ip);
        System.out.println("\nResult 3 = "+DecToBin.recursion(ip));
    }
}
于 2016-06-02T18:10:48.833 回答
-2
    int n = 13;
    String binary = "";

    //decimal to binary
    while (n > 0) {
        int d = n & 1;
        binary = d + binary;
        n = n >> 1;
    }
    System.out.println(binary);

    //binary to decimal
    int power = 1;
    n = 0;
    for (int i = binary.length() - 1; i >= 0; i--) {
        n = n + Character.getNumericValue(binary.charAt(i)) * power;
        power = power * 2;
    }

    System.out.println(n);
于 2016-08-27T22:18:11.600 回答