简体   繁体   English

二进制到十进制Java转换器

[英]Binary to Decimal Java converter

I am creating a code that allows you to convert a binary number to a decimal number and vice versa. 我正在创建一个代码,允许您将二进制数转换为十进制数,反之亦然。 I have created a code that converts decimal to binary but can not workout how to implement the binary to decimal aspect. 我已经创建了一个将十进制转换为二进制的代码,但无法研究如何实现二进制到十进制的方面。

My code for decimal to binary is below: 我的十进制到二进制的代码如下:

import java.util.*;
public class decimalToBinaryTest
{
   public static void main (String [] args)
   {

      int n;
      Scanner in = new Scanner(System.in);

      System.out.println("Enter a positive interger");
      n=in.nextInt();

      if(n < 0)
      {
         System.out.println("Not a positive interger");
      }

      else
      {
         System.out.print("Convert to binary is: ");
         binaryform(n);
      }   
   }


   private static Object binaryform(int number)
   {

      int remainder;

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


      remainder= number % 2;
      binaryform(number >> 1);
      System.out.print(remainder);
      {
         return " ";
      }   
   }
}

An explanation to how the binary to decimal code work would help as well. 二进制到十进制代码如何工作的解释也会有所帮助。

I have tried the method of the least significant digit*1 then the next least *1*2 then *1*2*2 but can not get it to work. 我已经尝试了最低有效digit*1的方法,然后是下一个最低*1*2然后*1*2*2但无法使其工作。

Thank you @korhner I used your number system with arrays and if statements. 谢谢@korhner我用你的数字系统和数组和if语句。

This is my working code: 这是我的工作代码:

import java.util.*;
public class binaryToDecimalConvertor
{
   public static void main (String [] args)
   {
   int [] positionNumsArr= {1,2,4,8,16,32,64,128};
   int[] numberSplit = new int [8];
   Scanner scanNum = new Scanner(System.in);
   int count1=0;
   int decimalValue=0;


   System.out.println("Please enter a positive binary number.(Only 1s and 0s)");
   int number = scanNum.nextInt();

   while (number > 0) 
   {     
      numberSplit[count1]=( number % 10);
      if(numberSplit[count1]!=1 && numberSplit[count1] !=0)
      {
      System.out.println("Was not made of only \"1\" or \"0\" The program will now restart");
      main(null);
      }
      count1++; 
      number = number / 10;
   }

   for(int count2 = 0;count2<8;count2++)
   {
   if(numberSplit[count2]==1)
   {
   decimalValue=decimalValue+positionNumsArr[count2];
   }
   }

   System.out.print(decimalValue);

   }
}

sample: 样品:

00000100 00000100

0 - 1 0 - 1
0 - 2 0 - 2
1 - 4 1 - 4
0 - 8 0 - 8
0 - 16 0 - 16
0 - 32 0 - 32
0 - 64 0 - 64
0 - 128 0 - 128

Sum values with bit 1 = 4 位1 = 4的求和值

Good luck! 祝好运!

int decimal = Integer.parseInt("101101101010111", 2); 

or if you prefer to doit your self 或者如果你喜欢自己动手

double output=0;

for(int i=0;i<str.length();i++){

   if(str.charAt(i)== '1')
     output=output + Math.pow(2,str.length()-1-i);

}

Here is a program which does that. 这是一个程序。
Make sure the integers you give to int and not too large. 确保你给int的整数而不是太大。

import java.util.Scanner;


public class DecimalBinaryProgram {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (true){
            System.out.println("Enter integer in decimal form (or # to quit):");
            String s1 = in.nextLine();
            if ("#".equalsIgnoreCase(s1.trim())){
                break;
            }
            System.out.println(decimalToBinary(s1));
            System.out.println("Enter integer in binary form  (or # to quit):");
            String s2 = in.nextLine();
            if ("#".equalsIgnoreCase(s2.trim())){
                break;
            }
            System.out.println(binaryToDecimal(s2));
        }
    }

    private static String decimalToBinary(String s){
        int n = Integer.parseInt(s, 10);
        StringBuilder sb = new StringBuilder();

        if (n==0) return "0";
        int d = 0;
        while (n > 0){
            d = n % 2;
            n /= 2;
            sb.append(d);
        }
        sb = sb.reverse();
        return sb.toString();
    }

    private static String binaryToDecimal(String s){
        int degree = 1;
        int n = 0;
        for (int k=s.length()-1; k>=0; k--){
            n += degree * (s.charAt(k) - '0');
            degree *= 2;
        }
        return n + "";
    }

}

Of course for this method binaryToDecimal you can just do: 当然对于这个方法binaryToDecimal你可以这样做:

private static String binaryToDecimal(String s){
    int n = Integer.parseInt(s, 2);
    return n + "";
}

but I wanted to illustrate how you can do that explicitly. 但我想说明你如何明确地做到这一点。

do you want this? 你想要这个吗?

private double dec(String s, int i) {
    if (s.length() == 1) return s.equals("1") ? Math.pow(2, i) : 0;
    else return (s.equals("1") ? Math.pow(2, i) : 0) + dec(s.substring(0, s.length() - 1), i - 1);
}


dec("101011101",0);

This is a version of a binary to decimal converter. 这是二进制到十进制转换器的一个版本。 I have used plenty of comments also. 我也使用了很多评论。 Just taught I would like to share it. 刚刚教过我想分享一下。 Hope it is of some use to somebody. 希望它对某些人有用。

import java.util.Scanner;

 public class BinaryToDecimal
 {
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a binary number: ");
        String binary = input.nextLine(); // store input from user
        int[] powers = new int[16]; // contains powers of 2
        int powersIndex = 0; // keep track of the index
        int decimal = 0; // will contain decimals
        boolean isCorrect = true; // flag if incorrect input

       // populate the powers array with powers of 2
        for(int i = 0; i < powers.length; i++)
            powers[i] = (int) Math.pow(2, i);

        for(int i = binary.length() - 1; i >= 0; i--)
        {
            // if 1 add to decimal to calculate
            if(binary.charAt(i) == '1')
                decimal = decimal + powers[powersIndex]; // calc the decimal

            else if(binary.charAt(i) != '0' & binary.charAt(i) != '1')
            {
                isCorrect = false; // flag the wrong input
                break; // break from loop due to wrong input
            } // else if

            // keeps track of which power we are on
            powersIndex++; // counts from zero up to combat the loop counting down to zero
        } // for

        if(isCorrect) // print decimal output
            System.out.println(binary + " converted to base 10 is: " + decimal);
        else // print incorrect input message
            System.out.println("Wrong input! It is binary... 0 and 1's like.....!");

    } // main
 } // BinaryToDecimal

I've written a converter that accepts both strings and ints. 我写过一个接受字符串和整数的转换器。

public class Main {

    public static void main(String[] args) {

        int binInt = 10110111;
        String binString = "10110111";
        BinaryConverter convertedInt = new BinaryConverter(binInt);
        BinaryConverter convertedString = new BinaryConverter(binString);

        System.out.println("Binary as an int, to decimal: " + convertedInt.getDecimal());
        System.out.println("Binary as a string, to decimal: " + convertedString.getDecimal());

    }

}

public class BinaryConverter {

    private final int base = 2;
    private int binaryInt;
    private String binaryString;
    private int convertedBinaryInt;

    public BinaryConverter(int b) {
        binaryInt = b;
        convertedBinaryInt = Integer.parseInt(Integer.toString(binaryInt), base);
    }

    public BinaryConverter(String s) {
        binaryString = s;
        convertedBinaryInt = Integer.parseInt(binaryString, base);
    }

    public int getDecimal() {
        return convertedBinaryInt;
    }

}
public static void main(String[] args)
{
    System.out.print("Enter a binary number: ");
    Scanner input = new Scanner(System.in);
    long num = input.nextLong();

    long reverseNum = 0;
    int decimal = 0;
    int i = 0;

    while (num != 0)
    {
        reverseNum = reverseNum * 10;
        reverseNum = num % 10;
        decimal = (int) (reverseNum * Math.pow(2, i)) + decimal;
        num = num / 10;
        i++;
    }
    System.out.println(decimal);

}

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

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