Java二进制转十进制转换器

3

我正在创作一段代码,可以让你将二进制数转换成十进制数,也可以反过来。我已经写好了将十进制数转换为二进制数的代码,但不知道如何实现将二进制数转换为十进制数。

以下是我编写的十进制转二进制代码:

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

如何将二进制代码转换为十进制代码的解释也会有所帮助。
我曾尝试过最不重要的数字*1,然后是接下来最不重要的*1*2,然后是*1*2*2,但无法使其正常工作。
谢谢@korhner,我使用了您的带有数组和if语句的数字系统。
这是我的可运行代码:
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);

   }
}
7个回答

6

样例:

00000100

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

将其拥有的位 1 等于 4 的数值相加。

祝你好运!


1
提供有用答案却未公布解决方案是值得肯定的。问题似乎类似于作业或练习,所以我认为这应该是被接受的答案。 - Andreas Aumayr

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

或者如果你更喜欢自己动手

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

}

抱歉,但是为了我正在做的事情,我不能只这样做。我需要一个带有循环和其他东西的算法。 - userX
maths.pow是什么? - userX
但是我想要的是一个使用我在问题中提出的方法的程序。 - userX
我没听懂你的意思,你只需要添加一个函数体和返回类型。 - Saddam Abu Ghaida

1
这里有一个能够实现此功能的程序。
确保您输入的整数不要过大。
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 + "";
    }

}

当然,对于这个方法 binaryToDecimal,你只需执行以下操作:
private static String binaryToDecimal(String s){
    int n = Integer.parseInt(s, 2);
    return n + "";
}

但我想说明如何明确地完成这件事。

谢谢。我有点明白这是怎么回事了。等我回家后,我会尝试把它正确地解决掉。 - userX

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

}

请仅返回翻译过的文本:此代码的作用和为什么可以帮助OP,也请添加解释,而不只是复制您的代码。 - David Medenjak

0

你需要这个吗?

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

当您提交答案时,应确保您完全理解问题 - 您应使用注释来实现这一点。 - Jakub Kubrynski

0
我写了一个转换器,可以接受字符串和整数。
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;
    }

}

0
这是一个二进制转十进制转换器的版本。我也使用了很多注释。只是想分享一下。希望对某些人有所帮助。
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接