二进制到十进制Java转换器

时间:2014-02-15 12:17:13

标签: java

我正在创建一个代码,允许您将二进制数转换为十进制数,反之亦然。我已经创建了一个将十进制转换为二进制的代码,但无法研究如何实现二进制到十进制的方面。

我的十进制到二进制的代码如下:

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

   }
}

7 个答案:

答案 0 :(得分:6)

样品:

00000100

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

位1 = 4

的和值 祝你好运!

答案 1 :(得分:4)

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

或者如果你喜欢自己做的话

答案 2 :(得分:1)

这是一个这样做的程序 确保你给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 + "";
}

但我想说明你如何明确地做到这一点。

答案 3 :(得分: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);

答案 4 :(得分: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

答案 5 :(得分:0)

我已经编写了一个接受字符串和整数的转换器。

carImage: { _id: 555a1ae275c52a072dffaa1a,
data: 
{ _bsontype: 'Binary',
 sub_type: 0,
 position: 69702,
 buffer: <Buffer ff d8 ff e0 00 10 4a 46 49 46 00 01 02 00 00 01 00 01 00 00 ff ed 00 9c 50 68 6f 74 6f 73 68 6f 70 20 33 2e 30 00 38 42 49 4d 04 04 00 00 00 00 00 80 1c ...> },
contentType: 'image/jpg' }
contentType: undefined
Data: undefined

答案 6 :(得分:0)

'