十进制转换为二进制的Java(Converting Decimal to Binary Java)

2019-07-19 16:15发布

我想十进制转换为使用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中?

Answer 1:

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


Answer 2:

Integer.toBinaryString()是一个内置的方法,并会做的相当不错。



Answer 3:

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

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

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

其中n =十进制数。



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


Answer 5:

我只想补充,任何人谁使用:

   String x=Integer.toBinaryString()

得到的二进制数字符串,并希望该字符串转换成int类型。 如果您使用

  int y=Integer.parseInt(x)

你会得到一个NumberFormatException异常错误。

我所做的,以串x转换为整数,先转换每​​个单独字符的字符串x到一个字符在for循环中。

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

然后我转换每个字符回个体字符串,

  String u=String.valueOf(t);

然后被解析每个String成整数。

ID图1d发布此,因为我花了一段时间来弄清楚如何获得二进制如01010101成整数形式。



Answer 6:

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

    }

}


Answer 7:

以下十进制转换为二进制与时间复杂度: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());
}


Answer 8:

如果你想扭转计算的二进制形式,你可以使用StringBuffer类和简单地使用reverse()方法。 这里是一个将解释其用途和计算二进制样本程序

公共类二进制{

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

}



Answer 9:

它可能看起来很可笑,但如果u想试试效用函数

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

必须有一些实用的方法直接做到这一点,我不记得。



Answer 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

二进制= 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



Answer 11:

比高效的程序相当简单,但它的工作。

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


Answer 12:

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


Answer 13:

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


Answer 14:

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


Answer 15:

我只是这解决了我自己,我想分享我的答案,因为它包含二进制逆转,然后转换为十进制。 我不是一个非常有经验的编码器,但希望这将有助于给别人。

我所做的就是推二进制数据到堆栈,因为我是将其转换,然后弹出它关闭扭转它,并将其转换回十进制。

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

    }
}


Answer 16:

您可以使用包装类的概念为十进制直接转换为二进制,十六进制和octal.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

    }
}   


Answer 17:

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


Answer 18:

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

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


Answer 19:

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


Answer 20:

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

}


Answer 21:

其中最快的解决方案:

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


Answer 22:

更妙的是与StringBuilder的使用insert()在建十进制字符串的前面,而不调用反向()

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


Answer 23:

好了,你可以在循环中使用,这样,

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

您可以参考下面的例子中一些很好的解释,

十进制转换为二进制的例子。



Answer 24:

您所有的问题都可以用一行代码来解决! 为了将我的解决方案为您的项目,只需删除您binaryform(int number)方法,并更换System.out.print(binaryform(number));System.out.println(Integer.toBinaryString(number));



Answer 25:

无需任何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;
    }
}


Answer 26:

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

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


Answer 27:

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


文章来源: Converting Decimal to Binary Java