How to convert a hexadecimal number to a decimal number in Java

Source: Internet
Author: User

How to convert a hexadecimal number to a decimal number in Java

package com.swift;import java.util.Scanner;public class Hex2Decimal {    public static void main(String[] args) {        Scanner scan = new Scanner(System.in);        System.out.println("please enter a Hex:");        String hex = scan.nextLine();        hex = hex.toUpperCase();        System.out.println("The hex is:" + hex);        int decimal = 0;        for (int i = 0; i < hex.length(); i++) {            if (hexChar2Decimal(hex.charAt(hex.length() - 1 - i)) != -1) {                decimal = (int) (decimal + hexChar2Decimal(hex.charAt(hex.length() - 1 - i)) * Math.pow(16, i));            } else {                System.out.println("enter error, decimal will be zero!");                break;            }        }        System.out.println("decimal=" + decimal);    }    private static int hexChar2Decimal(char charAt) {        if (charAt >= 'A' && charAt <= 'F')            return charAt - 'A' + 10;        else if (charAt >= '0' && charAt <= '9')            return charAt-'0';        else            return -1;    }}

Hexadecimal AF3 conversion principle: 3*16 ^ 0 + F * 16 ^ 1 + A * 16 ^ 2 where ^ represents A power operation, F and A must be converted to decimal numbers 15 and 10.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.