如何在Java中从任何基数转换为基数10

drg*_*gPP 4 java

我是Java新手.我想编写一个程序,只使用aritmetic操作将基数2,3,4,5,6,7,8,9,16转换为基数10.

我已经完成了从键盘读取字符串(如果数字是十六进制)并将其转换为整数,之后我做了一个while循环,将数字拆分为数字并反转它们.

现在我不知道如何使这个数字在幂0,1,2等处乘以2(在二进制情况下)以将数字转换为基数10.

例如1001(十进制数字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;        
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 15

用途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);
}
Run Code Online (Sandbox Code Playgroud)

反过来可以通过以下方式完成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);
}
Run Code Online (Sandbox Code Playgroud)