简体   繁体   English

将十进制转换为二进制 Java

[英]Converting Decimal to Binary Java

I am trying to convert decimal to binary numbers from the user's input using Java.我正在尝试使用 Java 将用户输入的十进制数转换为二进制数。

I'm getting errors.我收到错误。

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

How do I convert Decimal to Binary in Java?如何在 Java 中将十进制转换为二进制?

Integer.toBinaryString()是一个内置的方法,会做得很好。

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

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

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

where n = decimal number.其中 n = 十进制数。

Your binaryForm method is getting caught in an infinite recursion, you need to return if number <= 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);
    }
}

I just want to add, for anyone who uses:我只想补充一下,对于任何使用过的人:

   String x=Integer.toBinaryString()

to get a String of Binary numbers and wants to convert that string into an int.获取一个二进制数字字符串,并希望将该字符串转换为 int。 If you use如果你使用

  int y=Integer.parseInt(x)

you will get a NumberFormatException error.您将收到 NumberFormatException 错误。

What I did to convert String x to Integers, was first converted each individual Char in the String x to a single Char in a for loop.我所做的将字符串 x 转换为整数,首先将字符串 x 中的每个单独的 Char 转换为 for 循环中的单个 Char。

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

I then converted each Char back into an individual String,然后我将每个字符转换回一个单独的字符串,

  String u=String.valueOf(t);

then Parsed each String into an Integer.然后将每个字符串解析为一个整数。

Id figure Id post this, because I took me a while to figure out how to get a binary such as 01010101 into Integer form. Id figure Id 发布此信息,因为我花了一段时间才弄清楚如何将二进制文件(例如 01010101)转换为整数形式。

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

    }

}

The following converts decimal to Binary with Time Complexity : O(n) Linear Time and with out any java inbuilt function以下将十进制转换为具有时间复杂度的二进制: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());
}

If you want to reverse the calculated binary form , you can use the StringBuffer class and simply use the reverse() method .如果要反转计算的二进制形式,可以使用 StringBuffer 类并只需使用 reverse() 方法。 Here is a sample program that will explain its use and calculate the binary这是一个示例程序,将解释其使用并计算二进制

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

It might seem silly , but if u wanna try utility function这可能看起来很傻,但如果你想尝试效用函数

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

there must be some utility method to do it directly, I cant remember.必须有一些实用方法可以直接做到这一点,我不记得了。

In C# , but it's just the same as in Java :在 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);
}
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());
}

All your problems can be solved with a one-liner!您的所有问题都可以用一个班轮解决! To incorporate my solution into your project, simply remove your binaryform(int number) method, and replace System.out.print(binaryform(number));要将我的解决方案合并到您的项目中,只需删除您的binaryform(int number)方法,并替换System.out.print(binaryform(number)); with System.out.println(Integer.toBinaryString(number));System.out.println(Integer.toBinaryString(number)); . .

Binary to Decimal without using Integer.ParseInt():不使用 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); ;
    }

}

Output:输出:

Enter a binary number:输入一个二进制数:

1010 1010

Binary=1010 Decimal=10二进制=1010 十进制=10


Binary to Decimal using Integer.parseInt():使用 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));

    }

}

Output:输出:

Enter a binary number:输入一个二进制数:

1010 1010

Result: 10结果:10

A rather simple than efficient program , yet it does the job.一个相当简单而不是高效的程序,但它可以完成工作。

        Scanner sc = new Scanner(System.in);
        System.out.println("Give me my binaries");
        int str = sc.nextInt(2);
        System.out.println(str);
public static String convertToBinary(int dec)
{
    String str = "";
    while(dec!=0)
    {
        str += Integer.toString(dec%2);
        dec /= 2;
    }
    return new StringBuffer(str).reverse().toString();
}
/**
 * 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();
}

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

eg: (Convert 12 to binary)例如:(将 12 转换为二进制)

Integer.toString(12, 2)

Practically you can write it as a recursive function.实际上,您可以将其编写为递归函数。 Each function call returns their results and add to the tail of the previous result.每个函数调用都返回它们的结果并添加到前一个结果的尾部。 It is possible to write this method by using java as simple as you can find below:可以使用 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);
    }

}

Let us take a look how is the above recursion working:让我们看看上面的递归是如何工作的:

在此处输入图片说明

After calling convertDecimalToBinary method once, it calls itself till the value of the number will be lesser than 1 and return all of the concatenated results to the place where it called first.调用一次 convertDecimalToBinary 方法后,它会调用自己,直到数字的值小于 1,并将所有连接的结果返回到它首先调用的地方。

References:参考:

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

The better way of doing it:更好的方法:

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

I just solved this myself, and I wanted to share my answer because it includes the binary reversal and then conversion to decimal.我自己刚刚解决了这个问题,我想分享我的答案,因为它包括二进制反转,然后转换为十进制。 I'm not a very experienced coder but hopefully this will be helpful to someone else.我不是一个非常有经验的编码员,但希望这对其他人有帮助。

What I did was push the binary data onto a stack as I was converting it, and then popped it off to reverse it and convert it back to decimal.我所做的是在转换二进制数据时将其推入堆栈,然后将其弹出以反转它并将其转换回十进制。

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

    }
}

You can use the concept of Wrapper Classes to directly convert a decimal to binary,hexadecimal and octal.Below is a very simple program to convert decimal to reverse binary .Hope it contributes to your java knowledge 你可以使用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

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

This is a very basic procedure, I got this after putting a general procedure on paper.这是一个非常基本的程序,我是在将一般程序写在纸上之后得到的。

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

}

One of the fastest solutions:最快的解决方案之一:

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

Even better with StringBuilder using insert() in front of the decimal string under construction, without calling reverse(),使用 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();
}

Well, you can use while loop, like this,好吧,你可以像这样使用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);
   }
}

Output: 10100输出: 10100

No need of any java in-built functions.不需要任何 Java 内置函数。 Simple recursion will do.简单的递归就可以了。

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

Here is the conversion of Decimal to Binary in three different ways这是十进制到二进制的三种不同方式的转换

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM