zoukankan      html  css  js  c++  java
  • 十六进制转化为十进制

    package lsh.element.numbersystem;
    
    import java.util.Scanner;
    
    /**
     * 
     * @desc 有意思的地方:两种思想得到的结果都是正确的,但是超出int类型最大之后,错误值却不同
     *      
     * @author 
     *      LSH
     * 2018年9月23日
     */
    public class HexToDecimalConversion {
        
        
        public static void main(String[] args) {
            System.out.println((int)'0');
            Scanner input = new Scanner(System.in);
            System.out.print("请输入一个十六进制的数:");
            String hex = input.nextLine();
            System.out.println("【添位思想】你输入的十六进制数对应的数值是: "+hex+" = "+hexToDecimal_addBit(hex.toUpperCase()));
            System.out.println("【结果导向】你输入的十六进制数对应的数值是: "+hex+" = "+hexToDecimal_resultOriented(hex.toUpperCase()));
            input.close();
        }
        
        /**
         * 思想:结果为导向,从左到右,先高位后低位
         * @param hex
         * @return
         */
        public static int hexToDecimal_resultOriented(String hex) {
            int decimalValue = 0;
            //先计算高位,再计算低位
    //        for (int i = 0; i < hex.length(); i++) {
    //            char c = hex.charAt(i);
    //            decimalValue += (int) ((hexCharToDecimal(c))*Math.pow(16, hex.length()-1-i));
    //        }
            
            //先计算低位,再计算高位
            for (int i = hex.length()-1, j = 0; i >= 0; i--,j++) {
                char c = hex.charAt(i);
                decimalValue += (int) ((hexCharToDecimal(c))*Math.pow(16, j));
            }
            return decimalValue;
        }
        
        /**
         * 思想:添位思想,在原来数值的基础上每在后面添一位,原来的数值要乘以16
         *     添位思想,颇有蚕食进阶的味道,步步累进,更为高明
         * @param hex
         * @return
         */
        public static int hexToDecimal_addBit(String hex) {
            int decimalValue = 0;
            for (int i = 0; i < hex.length(); i++) {
                char c = hex.charAt(i);
                decimalValue = decimalValue*16 + hexCharToDecimal(c);
            }
            return decimalValue;
        }
    
        public static int hexCharToDecimal(char c) {
            if(c>='A' && c<='F') {
                return 10+c-'A';
            }
            return c-'0';
        }
    }
  • 相关阅读:
    Http record java
    Java String constructed from byte array has bad length
    Schema
    Scale-up(纵向扩展) vs Scale-out(横向扩展)
    数据同步
    JDBC and Oracle conn.commit and conn.setAutocommit not working properly
    DGIM
    Github Blog 搭建手册
    软件探索(一)
    经典书单 —— 人文社科
  • 原文地址:https://www.cnblogs.com/InformationGod/p/9693364.html
Copyright © 2011-2022 走看看