5

私はJavaが初めてです。算術演算のみを使用して、基数 2、3、4、5、6、7、8、9、16 から基数 10 に変換するプログラムを作成したいと考えています。

キーボードから文字列を読み取り (数値が 16 進数の場合)、それを整数に変換した後、数値を数字に分割して反転する while ループを作成しました。

今、この数字を2の累乗0、1、2など(バイナリの場合)で乗算して、数値を基数10に変換する方法がわかりません。

たとえば、1001 (10 進数で 9) は、1x2(pow 0)+0x2(pow 1)+0x2(pow 2)+1x2(pow 3) のようになります。

私のコード:

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Introduceti din ce baza doriti sa convertiti numarul: 2, 3, 4, 5, 6, 7, 8, 9, 16 ");
    int n = Integer.parseInt(br.readLine());
    Scanner scanner = new Scanner(System.in);
    System.out.println("Introduceti numarul care doriti sa fie convertit din baza aleasa ");
    String inputString = scanner.nextLine();
    if (n==2){
        int conv = Integer.parseInt(inputString);
        while (conv>0){
            System.out.println (conv%10);
            conv = conv/10;        
        }
    }
}
4

4 に答える 4

16

使用Integer.toString(int i, int radix):

int i = 1234567890;
for (int base : new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 16}) {
  String s = Integer.toString(i, base);
}

逆は次のように行うことができますInteger.parseInt(String s, int radix)

String s = "010101";
for (int base : new int[] { 2, 3, 4, 5, 6, 7, 8, 9, 16}) {
  Integer i = Integer.parseInt(s, base);
}
于 2013-10-26T13:05:40.230 に答える
-2
public class base2ToBase10Conversion {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Input Base 2 value:");
        int a = input.nextInt();
        int b = a/10000000;
        double c = b* Math.pow(2, 7);
        int d = Math.abs(a-(10000000*b));
        int e = d/1000000;
        double f = e* Math.pow(2,6);
        int g = Math.abs(d-(1000000*e));
        int h = g/100000;
        double i = h * Math.pow(2,5);
        int j = Math.abs(g-(100000*h));
        int k = j/10000;
        double l = k * Math.pow(2,4);
        int m = Math.abs(j-(10000*k));
        int n = m/1000;
        double o = n * Math.pow(2, 3);
        int p = Math.abs(m-(1000*n));
        int q = p/100;
        double r = q* Math.pow(2, 2);
        int s = Math.abs(p-(100*q));
        int t = s/10;
        double u = t* Math.pow(2,1);
        int v = Math.abs(s-(10*t));

        double base10 = c + f + i + l + o + r + u + v;

        System.out.println("Valuse in Base 10: " + base10);
    }
}
于 2015-08-30T12:06:17.380 に答える