簡體   English   中英

二進制到十進制Java轉換器

[英]Binary to Decimal Java converter

我正在創建一個代碼,允許您將二進制數轉換為十進制數,反之亦然。 我已經創建了一個將十進制轉換為二進制的代碼,但無法研究如何實現二進制到十進制的方面。

我的十進制到二進制的代碼如下:

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

二進制到十進制代碼如何工作的解釋也會有所幫助。

我已經嘗試了最低有效digit*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);

   }
}

樣品:

00000100

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

位1 = 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);

}

這是一個程序。
確保你給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 + "";
    }

}

當然對於這個方法binaryToDecimal你可以這樣做:

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

但我想說明你如何明確地做到這一點。

你想要這個嗎?

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

這是二進制到十進制轉換器的一個版本。 我也使用了很多評論。 剛剛教過我想分享一下。 希望它對某些人有用。

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

我寫過一個接受字符串和整數的轉換器。

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