欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java之實(shí)現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換案例講解

 更新時(shí)間:2021年08月26日 11:43:44   作者:izwqing  
這篇文章主要介紹了Java之實(shí)現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換案例講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下

寫了兩種十六進(jìn)制轉(zhuǎn)十進(jìn)制的方式,僅供參考。
基本思路:用十六進(jìn)制中每一位數(shù)乘以對應(yīng)的權(quán)值,再求和就是對應(yīng)的十進(jìn)制

方法一:

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class Test {
    /**
     * @param: [content]
     * @return: int
     * @description: 十六進(jìn)制轉(zhuǎn)十進(jìn)制
     */
    public static int covert(String content){
        int number=0;
        String [] HighLetter = {"A","B","C","D","E","F"};
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0;i <= 9;i++){
            map.put(i+"",i);
        }
        for(int j= 10;j<HighLetter.length+10;j++){
            map.put(HighLetter[j-10],j);
        }
        String[]str = new String[content.length()];
        for(int i = 0; i < str.length; i++){
            str[i] = content.substring(i,i+1);
        }
        for(int i = 0; i < str.length; i++){
            number += map.get(str[i])*Math.pow(16,str.length-1-i);
        }
        return number;
    }
    //測試程序
    public static void main(String... args) {
        Scanner input = new Scanner(System.in);
        String content = input.nextLine();
        if(!content.matches("[0-9a-fA-F]*")){
            System.out.println("輸入不匹配");
            System.exit(-1);
        }
        //將全部的小寫轉(zhuǎn)化為大寫
        content = content.toUpperCase();
        System.out.println(covert(content));
    }

}

利用了Map中鍵值對應(yīng)的關(guān)系

方法二:

import java.util.Scanner;

public class Test2 {
    /**
     * @param: [hex]
     * @return: int
     * @description: 按位計(jì)算,位值乘權(quán)重
     */
    public static int  hexToDecimal(String hex){
        int outcome = 0;
        for(int i = 0; i < hex.length(); i++){
            char hexChar = hex.charAt(i);
            outcome = outcome * 16 + charToDecimal(hexChar);
        }
        return outcome;
    }
    /**
     * @param: [c]
     * @return: int
     * @description:將字符轉(zhuǎn)化為數(shù)字
     */
    public static int charToDecimal(char c){
        if(c >= 'A' && c <= 'F')
            return 10 + c - 'A';
        else
            return c - '0';
    }
    //測試程序
    public static void main(String... args) {
        Scanner input = new Scanner(System.in);
        String content = input.nextLine();
        if(!content.matches("[0-9a-fA-F]*")){
            System.out.println("輸入不匹配");
            System.exit(-1);
        }
        //將全部的小寫轉(zhuǎn)化為大寫
        content = content.toUpperCase();
        System.out.println(hexToDecimal(content));

    }
}

方法二利用了字符的ASCII碼和數(shù)字的對應(yīng)關(guān)系

到此這篇關(guān)于Java之實(shí)現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換案例講解的文章就介紹到這了,更多相關(guān)Java之實(shí)現(xiàn)十進(jìn)制與十六進(jìn)制轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論