Convert hexadecimal to decimal, using java method

1. Introduction

The program reads a string from the console, and then calls the hexToDecimal method to convert a hexadecimal string to decimal. The characters can be uppercase or lowercase. Convert them to uppercase before calling the hexToDecimal method.
The defined hexToDecimal method returns an integer value. The length of this string is determined by the hex.length() method called.
The defined hexCharToDecimal returns the decimal value of a hexadecimal character.

Three. Code

package com.zhuo.base.com.zhuo.base;

import java.util.Locale;
import java.util.Scanner;

public class Hex2Dec {
    
    
    public static void main(String[] args) {
    
    
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a hex number: ");//提示用户输入字符串
        String hex = input.nextLine();
        System.out.println("The decimal value for has number " + hex + " is " + hexToDecimal(hex.toUpperCase(Locale.ROOT)));
    }
    public static int hexToDecimal(String hex) {
    
    
        int decimalValue = 0;
        for (int i = 0;i < hex.length();i++) {
    
    
            char hexChar = hex.charAt(i);
            decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
        }
        return  decimalValue;
    }
    public static  int hexCharToDecimal(char ch) {
    
    
        if (ch >= 'A' && ch <= 'F')
            return ch - 'A' + 10;
        else
            return ch - '0';
    }
}

Three. Results display

Enter a hex number: AB8C
The decimal value for has number AB8C is 43916

Process finished with exit code 0

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113621317