Java一个接受数字的十六进制表示并输出该数字的十进制表示的程序[重复]

时间:2021-09-15 16:58:00

This question already has an answer here:

这个问题在这里已有答案:

I got a program to convert integer to Hexadecimal, but I want the input to be Hexadecimal and convert to decimal. Please help....

我有一个程序将整数转换为十六进制,但我希望输入为十六进制并转换为十进制。请帮忙....

 int m; String Hdec="";
   while(m>0){
int rem;
rem=m%16;
if(rem>=0&rem<=9)
Hdec=rem+Hdec;
else if(rem==10)
    Hdec="A"+Hdec;
else if(rem==11)
    Hdec="B"+Hdec;
else if(rem==12)
    Hdec="C"+Hdec;
else if(rem==13)
            Hdec="D"+Hdec;
else if(rem==14)
    Hdec="D"+Hdec;
else if(rem==15)
    Hdec="D"+Hdec;
m=m/16;
     }
     sop(Hdec);

2 个解决方案

#1


1  

Somebody already implemented this, you can use for example

有人已经实现了这个,你可以使用例如

Integer.parseInt("1a", 16)

and will get the result 26.

并将获得结果26。

#2


1  

Try this approach:

试试这种方法:

import java.math.BigInteger;
import java.util.Scanner;

public class HexDec {

private static final int DECIMAL = 10;
private static final int HEXADECIMAL = 16;

public HexDec() {
    BigInteger hexNumber = new BigInteger(fetchInput(), HEXADECIMAL);

    System.out.println("Number in Decimal: " + hexNumber.toString(DECIMAL));
}

private String fetchInput() {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a hexadecimal number: ");
    String input = scanner.next();
    scanner.close();

    return input;
}

public static void main(String[] args) {
    new HexDec();
}
}

The above program can take even big hexadecimal integers and print their decimal integer representation even if it exceeds the limit of int and long variables.

上面的程序甚至可以采用大的十六进制整数并打印它们的十进制整数表示,即使它超过了int和long变量的限制。

#1


1  

Somebody already implemented this, you can use for example

有人已经实现了这个,你可以使用例如

Integer.parseInt("1a", 16)

and will get the result 26.

并将获得结果26。

#2


1  

Try this approach:

试试这种方法:

import java.math.BigInteger;
import java.util.Scanner;

public class HexDec {

private static final int DECIMAL = 10;
private static final int HEXADECIMAL = 16;

public HexDec() {
    BigInteger hexNumber = new BigInteger(fetchInput(), HEXADECIMAL);

    System.out.println("Number in Decimal: " + hexNumber.toString(DECIMAL));
}

private String fetchInput() {
    Scanner scanner = new Scanner(System.in);

    System.out.print("Enter a hexadecimal number: ");
    String input = scanner.next();
    scanner.close();

    return input;
}

public static void main(String[] args) {
    new HexDec();
}
}

The above program can take even big hexadecimal integers and print their decimal integer representation even if it exceeds the limit of int and long variables.

上面的程序甚至可以采用大的十六进制整数并打印它们的十进制整数表示,即使它超过了int和long变量的限制。