将十进制转换为二进制Java

时间:2013-02-09 03:29:41

标签: java binary decimal

我正在尝试使用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中将十进制转换为二进制?

29 个答案:

答案 0 :(得分:70)

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

答案 1 :(得分:33)

Integer.toString(n,8) // decimal to octal

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

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

其中n =十进制数。

答案 2 :(得分:12)

您的binaryForm方法陷入了无限递归,您需要在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);
    }
}

答案 3 :(得分:5)

/**
 * @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;
}

答案 4 :(得分:5)

我只是想为任何使用过的人添加:

   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,

  String u=String.valueOf(t);

然后将每个String解析为整数。

Id figure Id发布此信息,因为我花了一些时间来弄清楚如何将二进制文件(如01010101)转换为整数形式。

答案 5 :(得分: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);

    }

}

答案 6 :(得分: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());
}

答案 7 :(得分: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);
    }

}

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

enter image description here

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

参考:

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

答案 8 :(得分: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)

答案 9 :(得分:0)

public static void converToBinary(int dec)
{
    String str = "";
    while(dec!=0)
    {
        str = str + Integer.toString(dec%2);
        dec = dec/2;
    }
    System.out.println(new StringBuffer(str).reverse().toString());
}

答案 10 :(得分:0)

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

        Scanner sc = new Scanner(System.in);
        System.out.println("Give me my binaries");
        int str = sc.nextInt(2);
        System.out.println(str);

答案 11 :(得分:0)

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

/

<强>输出:

输入二进制数:

1010

二进制= 1010十进制= 10

使用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

结果:1​​0

答案 12 :(得分: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);
}

}

答案 13 :(得分:0)

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

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

必须有一些实用方法才能直接做到,我记不起来了。

答案 14 :(得分:-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;
    }

答案 15 :(得分:-1)

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

答案 16 :(得分:-1)

public class BinaryConvert{ 

    public static void main(String[] args){
        System.out.println("Binary Result: "+ doBin(45));
    }

    static String doBin(int n){
        int b = 2;
        String r = "";
        String c = "";

        do{
            c += (n % b);
            n /= b;         
        }while(n != 0);

        for(int i = (c.length() - 1); i >=0; i--){
            r += c.charAt(i);
        }

        return r;
    }
}

答案 17 :(得分:-1)

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

答案 18 :(得分:-1)

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

import java.util.Scanner;

public class DecimalToBinaryExample
{
    public static void main(String[] args)
    {
        int num;
        int a = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a decimal number : ");
        num = sc.nextInt();
        int binary[] = new int[100];

        while(num != 0)
        {
            binary[a] = num % 2;
            num = num / 2;
            a++;
        }

        System.out.println("The binary value is : ");
        for(int b = a - 1; b >= 0; b--)
        {
            System.out.println("" + binary[b]);
        }
        sc.close();
    }
}

您可以参考以下示例获得一些好的解释,

convert decimal to binary示例。

答案 19 :(得分:-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();
}

答案 20 :(得分:-1)

你可以使用Wrapper Classes的概念直接将十进制转换为二进制,十六进制和八进制.Below是一个非常简单的程序,用于将十进制转换为反向二进制。希望它有助于你的java知识

public class decimalToBinary
{
   public static void main(String[] args)
   {
       int a=43;//input
       String string=Integer.toBinaryString(a);  //decimal to binary(string)
       StringBuffer buffer = new StringBuffer(string);  //string to binary
       buffer.reverse(); //reverse of string buffer
       System.out.println(buffer);  //output as string

    }
}   

答案 21 :(得分:-1)

mMask.setVisibility(View.VISIBLE); // blocks children
mMask.setVisibility(View.GONE); // children clickable

答案 22 :(得分:-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());
            }
        }

    }
}

答案 23 :(得分:-1)

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

答案 24 :(得分:-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
                }
            }
        }
    }

答案 25 :(得分:-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);
    }
}

答案 26 :(得分:-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;
    }
}

答案 27 :(得分:-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);

答案 28 :(得分:-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));
    }
}