2

を使用せずに、2 進数を 10 進数に変換する簡単なプログラムを作成しようとしていますmath.pow()。これが私がこれまでに持っているものMath.powで、最後に使用しています:

import java.util.Scanner;
public class  Question1 {
  public static void main(String[] args) {
    System.out.println("Enter a binary number");
    Scanner inputKeyboard = new Scanner(System.in);
    String binaryNumber = inputKeyboard.nextLine();
    while (!checkIfBinary(binaryNumber)) {
      System.out.println("That is not a binary number.  Enter a binary number");
      binaryNumber = inputKeyboard.nextLine();
    }
    int decimalNumber = binaryToNumber(binaryNumber);
    System.out.println("Your number in base 10 is " + decimalNumber + ".");
  }

  public static boolean checkIfBinary(String input) {
    for (int i = 0; i < input.length(); i++) {
      if(input.charAt(i) != '0' && input.charAt(i) != '1') {
        return false;
      }
    }
    return true;
  }

  public static int binaryToNumber(String numberInput) {
    int total = 0;
    for (int i = 0; i < numberInput.length(); i++) {
      if (numberInput.charAt(i) == '1')  {
        total += (int) Math.pow(2, numberInput.length() - 1 - i);
      }
    }
    return total;
  }
}

なしでべき乗を行う際に問題が発生していmath.powます。ループを使用する必要があることはわかっており、このループは 2 倍する必要がありますnumberInput.length() - 1 - i。しかし、私はこれを実装するのに苦労しています。

4

4 に答える 4

3

Stringあなたを整数に解析し、それをベースにします2

int decimalValue = Integer.parseInt(yourStringOfBinary, 2);

ただし、整数の最大値は2^31-1次のバイナリであることに注意してください。

1111111111111111111111111111111

したがって、java.lang.NumberFormatException上記よりも大きなバイナリ値を入力するとエラーが発生します。この問題を解決するにはBigInteger

int decimalValue = new BigInteger(yourBinaryString, 2).intValue()
于 2015-02-03T19:45:16.460 に答える
2

Integerbase入力した数値の を指定して、これを行うことができます。

Integer.parseInt("101101101010111", 2); 

これは使用しませんMath.pow:)

これはあなたが望んでいたものではないかもしれませんが、とにかく誰かを助けるかもしれません.

于 2015-02-03T19:45:16.440 に答える
1

Integer.parseInt を使用できます。

同様の質問がここで回答されています:

バイナリ文字列値を 10 進数に変換する方法

唯一の違いは、上記の回答では、文字列 ("01101") を 10 進整数に変換していることです。

Javadoc Integer.parseIntも参照してください。

于 2015-02-03T19:55:44.060 に答える
1

文字列の末尾から逆方向に作業し、各文字の累乗を段階的に計算します。

public static int binaryToNumber (String numberInput) {
    int currentPower = 1;
    int total = 0;

    for (int i = numberInput.length() - 1; i >= 0; i--) {
        if (numberInput.charAt(i) == '1')  {
            total += currentPower;
        }
        currentPower *= 2;
    }

    return total;
}
于 2015-02-03T19:47:15.397 に答える