2014-02-15 29 views
3

我創建一個代碼,可以讓你的二進制數轉換爲十進制數,反之亦然。我已經創建了一個將十進制轉換爲二進制的代碼,但不能解決如何將二進制實現爲十進制方面的問題。二進制到十進制的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); 

    } 
} 

回答

6

樣本:

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

薩姆值與位1 = 4

良好運氣!

+1

+1 。問題看起來像一個家庭作業/練習,所以在我看來這應該是被接受的答案。 –

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

,或者如果你喜歡DOIT你的自我

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

} 
+0

很抱歉,但這樣做,我不能justdo什麼IM。我需要一個循環和東西的算法 – userX

+0

檢查更新的答案 –

+0

maths.pow做什麼?一些 – userX

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

當你發佈答案時,你應該確保你完全理解問題 - 你應該使用評論來實現。 –

+0

這不提供問題的答案。要批評或要求作者澄清,請在其帖子下方留言。 –

+0

謝謝@JakubKubrynski –

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

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

+0

謝謝。我有點得知這是如何工作的。當我回到家時,我會盡力解決它。 – userX

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

} 
+0

請另外添加一個說明此代碼的作用,以及爲什麼它可以幫助OP,而不僅僅是粘貼代碼 –