zl程序教程

您现在的位置是:首页 >  其他

当前栏目

算法练习题(四)——十六进制和十进制的相互转换

转换算法十进制 相互 练习题 十六进制
2023-06-13 09:18:38 时间

十进制转十六进制

import java.util.Scanner;
public class Main_10 {
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        int a=scanner.nextInt();
        int i=a/16;
        int temp=a%16;
        if (temp<10){
            System.out.println(i+""+temp);
        }else if (temp==10){
            System.out.println(i+"A");
        }else if (temp==11){
            System.out.println(i+"B");
        }else if (temp==12){
            System.out.println(i+"C");
        }else if (temp==13){
            System.out.println(i+"D");
        }else if (temp==14){
            System.out.println(i+"E");
        }else if (temp==15){
            System.out.println(i+"F");
        }
    }
}

十六进制转十进制

import java.util.Scanner;
public class Main_11_2 {

    public static int hexCharToDecimal(char hexChar)
    {
        if(hexChar>='A'&&hexChar<='F'){
            return  hexChar;
        }
        else{
            /**
             *  根据Ascii码
             *  'A'~'Z'字母对应的十进制是 65-90
             *  'a'~'z'对应的十进制是 97-122
             */
            return hexChar-'0';
            //切记不能写成int类型的0,因为字符'0'转换为int时值为48
        }
    }

    /*decimal 十进制*/
    public static int decimalMethod(String str)
    {
        int decimalValue=0;
        /*利用charAt()方法 分别取出每个字符*/
        for(int i=0;i<str.length();i++)
        {
            char hexChar=str.charAt(i);
            /*向hexCharToDecimal()方法中传入 十六进制字符herChar */
            decimalValue=decimalValue*16+hexCharToDecimal(hexChar);
        }
        return decimalValue;
    }

    public static void main(String[] args) {
        Scanner input=new Scanner(System.in);
        /*her 十六进制*/
        String hex=input.nextLine();
        /*向decimalMethod()方法中传入  键盘输入十六进制字符串hex */
        System.out.println("十进制为:"+decimalMethod(hex.toUpperCase()));
    }
}